今私は、3つの異なるデータテンプレート、3つのビューモデル、およびアイテムテンプレートセレクタを持つカスタムアイテムコントロールを使用しています。アイテムセレクタアイテムは異なるデータテンプレートを使用しますが、ビューモデルを共有する必要があります
すべて機能していますが、このコードの改善を検討しています。ここでは3つのデータのテンプレートです:
<DataTemplate x:Key="RefreshDevicesDataTemplate">
<Grid Margin="5,0">
<myApp:myAppButton Name="RefreshButton" Command="{Binding Command}" ToolTip="Refresh Devices" Style="{StaticResource TransparentStyle}">
<Rectangle x:Name="RefreshRectangle" Width="20" Height="20" ToolTip="{Binding ToolTip}" Fill="{Binding IconBrush}" Opacity="1" Margin="0,0,0,6"/>
</myApp:myAppButton>
</Grid>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding IsWaiting}" Value="True">
<Setter Property="Opacity" Value="0.5" TargetName="RefreshRectangle" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
<DataTemplate x:Key="DeviceDataTemplate">
<Grid Margin="5,0">
<Rectangle x:Name="IconRectangle" Width="20" Height="20" Fill="{Binding IconBrush}" Opacity="0.5" ToolTip="{Binding DeviceName}"/>
</Grid>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding IsConnected}" Value="True">
<Setter Property="Opacity" Value="1" TargetName="IconRectangle" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
<DataTemplate x:Key="CommandDataTemplate">
<Grid Margin="5,0">
<myApp:myAppButton Style="{DynamicResource ChromelessButtonStyle}" Foreground="White" Content="{Binding CommandName, Converter={StaticResource LowerCaseConverter}}"
Command="{Binding Command}" CommandParameter="{Binding CommandParameter}" ToolTip="{Binding ToolTip}"
FontFamily="Marlett"/>
</Grid>
</DataTemplate>
そして、私のテンプレートセレクタ:
<models:WindowCommandItemTemplateSelector x:Key="WindowCommandTemplateSelector" DeviceTemplate="{StaticResource DeviceDataTemplate}" CommandTemplate="{StaticResource CommandDataTemplate}" RefreshCommandTemplate="{StaticResource RefreshDevicesDataTemplate}"/>
public override DataTemplate SelectTemplate(object item, DependencyObject container) {
DataTemplate resultTemplate = null;
if (item is DeviceViewModel)
{
resultTemplate = DeviceTemplate;
}
else if (item is WindowCommandViewModel) // I need two view models because I can't know which template to use with just one class.
{
resultTemplate = CommandTemplate;
}
else if (item is RefreshCommandViewModel) // here too
{
resultTemplate = RefreshCommandTemplate;
}
return resultTemplate;
}
テンプレートセレクタはちょうどに渡されたビューモデルに基づいたテンプレートを選択
。最後にitemscontrolを指定します:
<myApp:myAppWindow.WindowCommands>
<myApp:WindowCommands ItemTemplateSelector="{StaticResource WindowCommandTemplateSelector}" ItemsSource="{Binding WindowCommands}" />
</myApp:myAppWindow.WindowCommands>
これらのデータテンプレートごとに異なるビューモデルがありますが、実際にはRefreshButton
とCommandDataTemplate
は異なるテンプレートのボタンです。私はIsWaiting
のようないくつかの異なるバインディングを持っていますが、それらは親ビューモデルで扱うことができます。
このitemscontrolにカスタムテンプレートを追加し続けるには、ビューモデルとデータテンプレートの間に1-1の対応が必要ですか?
私はいくつかの静的プロパティを作成し、それをチェックできますか?これを行うには、より多くのWPF-y方法がありますか?私はとても新しいです。ありがとう。
私はそれを見逃していました。私のビューモデルには、単にデータテンプレートセレクタをチェックすることができるコマンド名があります...ありがとう。 – wdonahoe