【发布时间】:2021-04-29 03:17:09
【问题描述】:
我正在使用 MVVM 设计模式,我想根据项目源对象的类型更改要使用的控件类型。 我的项目来源类型代码:
public class PropertyItemVM : ViewModelBase
{
// Some base code for all basic property items
}
public class StringValuePropertyItemVM : PropertyItemVM
{
// Code to correctly create string value property item
}
public class ComboBoxPropertyItemVM : PropertyItemVM
{
// Code to correctly create combo box property item
}
在我的视图模型中,我将属性列表绑定到 xaml
public ObservableCollection<PropertyItemVM> Properties { get; set; }
此集合包含StringValuePropertyItemVM 和ComboBoxPropertyItemVM 两种类型的对象。
现在我想要实现的是,根据我想决定 xaml 是否包含 TextBox 或 ComboBox 的对象类型。
我的 xaml 代码:
<StackPanel>
<!--Items Control containing all list of properties to be shown-->
<ItemsControl x:Name="Local" ItemsSource="{Binding Properties}" Background="White">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<Label Content="{Binding Label}"
IsEnabled="{Binding IsEnabled}"
Grid.Column="0"/>
<!-- Here based on type need to change the TextBox with ComboBox-->
<TextBox Text="{Binding Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Grid.Column="1"
IsEnabled="{Binding IsEnabled}"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
在一些帮助下,我发现我可以为这两种类型提供不同的数据模板并在它们之间切换,但是我找不到如何做到这一点。谁能帮我解决这个问题?
【问题讨论】:
-
看来,你需要自己的
DataTemplateSelector
标签: c# wpf xaml user-interface mvvm