WPF
MVVMパターンを使い始めたばかりです。私はMVVMに関連するいくつかの資料を調べました。
ただし、私が取り組まなければならないプロジェクトには、私が読んだものとは非常に異なるように見えるMVVMの実装があります(おそらく間違っているかもしれませんが、よくわかりません)。
実装には、ビュー内のすべてのコントロールが "Style" 要素にある ResourceDictionary として実装されたすべてのビュー (コントロールまたはウィンドウ) があります。
このような ResourceDictionary のコード ビハインドには、すべての DependencyProperty とコマンドがあります (ViewModel には他のクラスはありません)。また、クラス (コード ビハインド) は、Windows.Controls.Control クラスから何らかの方法で継承します。
これは正しい実装ですか? そうでない場合、これが間違った実装であることを証明する理由は何ですか。
私が間違っているかもしれませんが、私が見る理由は次のとおりです。
- ビューの実装
ResourceDictionary
は正しくなく、リソースはカスタム ビューを作成するためのものではありません。 - コード ビハインドに最小限のコードを含めることは、疎結合アーキテクチャを可能にする MVVM の重要な側面の 1 つです。
- すべてのビューは Windows.Controls.Control から継承されるため、ビューの単体テスト ケースを作成するのは困難です。
私は正しいですか、それともこの実装が正しくない理由がいくつかあります (または、私が間違っているので、MVVM を に実装する方法になる可能性がありますWPF
)。
ご意見をお待ちしております。
以下はサンプルコードです: (XAML)
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Presentation"
>
<Style TargetType="{x:Type local:FirstControl}">
<Setter Property="IsTabStop" Value="False"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:FirstControl}">
<ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" Height="490" DataContext="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Mode=OneTime}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="TEST TEXT" FontWeight="DemiBold"/>
<Button Command="{Binding Path=CloseCommand, Mode=OneTime}"
Width="48" Height="30"/>
</StackPanel>
</ScrollViewer>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
コードビハインド:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
namespace Presentation
{
/// <summary>
/// View-model
/// </summary>
public class FirstControl : Control
{
static FirstControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(FirstControl), new FrameworkPropertyMetadata(typeof(FirstControl)));
}
public FirstControl()
{
CloseCommand = new DelegateCommand(OnCloseCommand);
}
private void OnCloseCommand()
{
// Write code to close application.
}
public static readonly DependencyProperty CloseCommandProperty = DependencyProperty.Register("CloseCommand", typeof(ICommand), typeof(FirstControl));
public ICommand CloseCommand
{
get { return (ICommand)GetValue(CloseCommandProperty); }
set { SetValue(CloseCommandProperty, value); }
}
}
}
お役に立てれば。
はDelegateCommand
、パラメーターとして渡されるメソッドにコマンド ロジックを委譲できるようにするクラスです。