我有一个通用控件,它根据 ViewModel 内的 type 属性显示编辑器。目前它是使用 Control
、ControlTemplate
和 DataTrigger
实现的,如下所示 -
<Control
x:Name="MainControl"
Grid.Column="1"
TargetUpdated="OnTargetUpdated">
<Control.Style>
<Style>
<Style.Triggers>
<DataTrigger
Binding="{Binding Path=EditorType}"
Value="{x:Static view:EditorType.Bool}">
<Setter
Property="Control.Template"
Value="{StaticResource boolTemplate}" />
</DataTrigger>
<DataTrigger
Binding="{Binding Path=EditorType}"
Value="{x:Static view:EditorType.Text}">
<Setter
Property="Control.Template"
Value="{StaticResource textTemplate}" />
</DataTrigger>
<DataTrigger
Binding="{Binding Path=EditorType}"
Value="{x:Static view:EditorType.Integer}">
<Setter
Property="Control.Template"
Value="{StaticResource integerTemplate}" />
</DataTrigger>
...
...
</Style.Triggers>
</Style>
</Control.Style>
</Control>
现在,使用 ContentPresenter
、DataTemplate
和 DataTemplateSelector
也可以实现同样的效果 -
<local:EditorTemplateSelector
BoolEditorTemplate="{StaticResource boolTemplate}"
TextEditorTemplate="{StaticResource textTemplate}"
IntegerEditorTemplate="{StaticResource integerTemplate}"
...
...
x:Key="EditorTemplateSelector">
</local:EditorTemplateSelector>
<ContentPresenter
ContentTemplateSelector="{Binding Source={StaticResource EditorTemplateSelector}}"
Content="{Binding}"
TargetUpdated="OnTargetUpdated">
</ContentPresenter>
// Template selector returning appropriate template based on type
我觉得第二种方法,使用 DataTemplateSelector
更好,但想知道你的情况 -
- 哪一个更好?为什么?
- 两者的性能会有差异吗?
最佳答案
我听说 DataTemplateSelectors
如果它们基于的值发生变化,则不会更新模板,因此我通常不使用它们。
我的首选方法实际上是使用 DataTemplates。
<MyControl.Resources>
<DataTemplate TargetType="{x:Type local:BooleanModel}">
<local:BooleanView />
</DataTemplate>
<DataTemplate TargetType="{x:Type local:IntegerModel}">
<local:IntegerView />
</DataTemplate>
...
</MyControl.Resources>
其次,如果我想根据属性而不是对象类型更改模板,我倾向于使用DataTriggers
。这是因为,如果该属性发生更改,PropertyChange 通知将自动告诉 UI 它已更改并更新模板。我不相信 DataTemplateSelectors 会自动执行此操作。我还更喜欢在 XAML 中查看模板选择逻辑,而不是将其隐藏在 TemplateSelector 文件中,但这只是个人喜好。
我的最后选择是使用DataTemplateSelector
。我几乎从不在 WPF 应用程序中使用它,尽管我经常在 Silverlight 中使用它,因为它不支持我首选的使用隐式 DataTemplates
的方法(尚)
我不知道两者之间有任何显着的性能差异,尽管如果有人能告诉我其他情况,我会很感兴趣。
关于c# - ControlTemplate 与 DataTrigger 对比带有 DataTemplateSelector 的 DataTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8926024/