我有ComboBox,其中填充了customTypes的集合。在comboBox更改时,我想加载/更改特定区域中的内容,以便为所选的ComboBox项加载相关数据(它可以是加载userControl的形式,或者我不介意为它指定DataTemplate)。
类似于这个问题WPF Load Control question。但在这个问题中,他正在讨论实际Listbox中的单个DataTemplates,而我正在讨论在ComboBox上填充某些窗口区域的变化。
我正在使用MVVM(而不是PRISM).Net 3.5。
答案 0 :(得分:2)
你可以使用ContentControl
,它是实际Content
的占位符,它是根据组合框选择动态决定的。
以下代码仅供参考
<Window ...>
<Window.Resources>
<MyView1 x:Key="MyView1" />
<MyView2 x:Key="MyView2" />
</Window.Resources>
...
<ComboBox x:Name="MyCombo">
<ComboBox.ItemsSource>
<sys:String>"MyView1"</sys:String>
<sys:String>"MyView2"</sys:String>
....
</ComboBox.ItemsSource>
</ComboBox>
...
<!-- This is where your region is loaded -->
<ContentControl>
<ContentControl.Style>
<Style TargetType="{x:Type ContentControl}">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=SelectedItem,
ElementName=MyCombo}"
Value="MyView1">
<Setter Property="Content"
Value="{StaticResource MyView1}"
</DataTrigger>
<DataTrigger Binding="{Binding Path=SelectedItem,
ElementName=MyCombo}"
Value="MyView2">
<Setter Property="Content"
Value="{StaticResource MyView2}"
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
</Window>
数据加载可以是MyView1
和MyView2
用户控件的构造函数或主UI的数据上下文视图模型的一部分。
答案 1 :(得分:1)
据我所知,问题是如何更改绑定到UI而不是DataTemplate的基础数据。
您可以使用EventSetter
代码处理后面的代码,您可以在其中为您提到的区域切换DataContext:
<ComboBox>
<ComboBox.Resources>
<Style TargetType="ComboBoxItem">
<EventSetter Event="Selector.SelectionChanged"
Handler="YourHandler"/>
</Style>
</ComboBox.Resources>
</ComboBox>
但是从MVVM的角度来看,它可能不是完美的解决方案,所以你可以引入你自己的ComboBox类,它具有Command意识,请参阅此SO帖子:WPF command support in ComboBox
通过这种方式,您可以使用Command将逻辑与UI分离。