DataTemplates に任せてください。
次の ViewModel を使用した単純なウィンドウが与えられます。
public sealed class ViewModel : INotifyPropertyChanged
{
private object _derper;
public event PropertyChangedEventHandler PropertyChanged = (o, e) => { };
public object Derper
{
get { return this._derper; }
set
{
this._derper = value;
PropertyChanged(this, new PropertyChangedEventArgs("Derper"));
}
}
public ICommand OnDerp { get; set; }
public ViewModel()
{
OnDerp = new DerpCommand(this);
}
}
プロパティ Derper のさまざまな値に対してさまざまな UI を表示したいと考えています。このプロパティは、DerpCommand によって設定されます。
public sealed class DerpCommand : ICommand
{
public event EventHandler CanExecuteChanged;
private readonly ViewModel _viewModel;
private int _count = 0;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
_viewModel.Derper = _count % 2 == 0 ?
(object)new Derp()
{ Herp = "Derped " + (++_count / 2 + 1) + " times." } :
new Herp()
{ Derp = "Herped " + (_count++ / 2 + 1) + " times." };
}
public DerpCommand(ViewModel viewModel)
{
this._viewModel = viewModel;
}
}
実行回数に基づいてとViewModel.Derper
のインスタンス間での値を切り替えるだけです。これらのモデルは単一のプロパティを持つ POCO であるため、これらのモデルの実装は省略します。退屈なもの。Herp
Derp
ここで、ViewModel.Derper
プロパティのタイプがDerp
の場合、モデルの値を表示する黒いテキストの前景に素敵なヤグルマギクの青い背景が必要です。タイプが の場合Herp
、黒の背景に白のテキストが必要です。したがってDataTemplates
、それぞれに以下を作成します。
<DataTemplate
DataType="{x:Type t:Derp}">
<TextBlock
Padding="50"
Background="CornflowerBlue"
Text="{Binding Herp}" />
</DataTemplate>
<DataTemplate
DataType="{x:Type t:Herp}">
<TextBlock
Padding="50"
Foreground="White"
Background="Black"
Text="{Binding Derp}" />
</DataTemplate>
DataTemplate
それぞれのDataContext
は、指定された のモデルのインスタンスであることに注意してくださいDataType
。
これらをどのように配線しますか?私たちはしません。DataTemplate
を追加してそのプロパティを にContentControl
バインドすることにより、適切な を表示する UI 内の領域を指定するだけです。UI全体は次のとおりです。Content
ViewModel.Derper
<Window
x:Class="DataTemplateExample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:t="clr-namespace:DataTemplateExample"
Title="DataTemplate example"
Height="350"
Width="525">
<Window.DataContext>
<t:ViewModel />
</Window.DataContext>
<Window.Resources>
<DataTemplate
DataType="{x:Type t:Derp}">
<TextBlock
Padding="50"
Background="CornflowerBlue"
Text="{Binding Herp}" />
</DataTemplate>
<DataTemplate
DataType="{x:Type t:Herp}">
<TextBlock
Padding="50"
Foreground="White"
Background="Black"
Text="{Binding Derp}" />
</DataTemplate>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition
Height="auto" />
</Grid.RowDefinitions>
<ContentControl
HorizontalAlignment="Center"
VerticalAlignment="Center"
Content="{Binding Derper}" />
<Button
Grid.Row="1"
Command="{Binding OnDerp}">Click me to derp</Button>
</Grid>
</Window>
そして、それはどのように見えるか:

結局のところ、Unity を使用して UI を接続したい場合は、Unity をDataTemplateSelector
使用してテンプレートを探す独自のものを作成できます。時間の無駄です。流れに乗ってください。