如何使用 DataTemplate + 触发器在视图之间切换 [英] How to switch between views using DataTemplate + Triggers
问题描述
我有一个要求,其中用户可以切换到以树或数据网格中的文本或流程图的形式查看分层数据.
I have a requirement where a where user can switch to view hierarchical data either as tree or as a text in datagrid or as FlowChart.
用户可以通过单击显示为:切换模式的切换按钮来执行此操作.我想以这样一种方式来完成所有这一切:它只能在 View 中处理,因为 ViewModel 在所有三种情况下都是相同的.
The user can do this by clicking a Toggle Button which say: Switch Mode. I want to do all this in such a way that it can be handled within the View only as ViewModel in all the three cases is the same.
如何基于触发器将 View 应用到我的 ViewModel.
How do I apply View to my ViewModel based on Trigger.
推荐答案
如果要显示的视图的状态保存在某个枚举属性中,您可以使用 ContentControl
和 DataTriggers
例如:
If the state of which view to show is saved in some enum property you could use a ContentControl
and DataTriggers
for example:
<ContentControl>
<ContentControl.Style>
<Style TargetType="{x:Type ContentControl}">
<Style.Triggers>
<DataTrigger Binding="{Binding ViewMode}" Value="TreeMode">
<Setter Property="Content">
<Setter.Value>
<uc:TreeModeView />
</Setter.Value>
</Setter>
</DataTrigger>
<DataTrigger Binding="{Binding ViewMode}" Value="GridMode">
<Setter Property="Content">
<Setter.Value>
<uc:GridModeView />
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
(由于样式只在一处使用,直接设置为ContentControl.Style
这样就可以了,如果你想在多个地方使用它,你应该设置ContentTemplate
代替,因为否则将只有一个视图实例被 WPF 不允许的样式的所有控件共享(当然 Content
需要设置为 something 用于要应用的模板))
(As the style is only used in one place, by setting it directly as ContentControl.Style
this will work, if you want to use it in more than one place you should set the ContentTemplate
instead, because otherwise there will only be one view instance shared by all controls with the style which is not allowed by WPF (of course Content
needs to be set to something for the template to be applied))
您也可以使用 ElementName
当然.相关值将是 True
、False
和 {x:Null}
.
You could also bind directly to IsChecked
of the ToggleButton
using ElementName
of course. The relevant values would then be True
, False
and {x:Null}
.
这篇关于如何使用 DataTemplate + 触发器在视图之间切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!