假设我在名为Attributes 的列表中有一些类对象。在我的例子中,我想绑定(bind)到这个列表并为每个类对象显示不同的用户控件。有办法做到这一点吗?
下面的代码似乎显示了所有类,不管它们的类型如何,如果我没有它的数据模板,我会假设它不会显示项目类型。
类
public class Attribute
{
public string Key { get; set; }
}
public class FloatAttr : Attribute
{
public float Value { get; set; }
public string Label { get; set; }
private float minValue { get; set; }
private float maxValue { get; set; }
}
public class IntAttr : Attribute
{
public int Value { get; set; }
public string Label { get; set; }
private float minValue { get; set; }
private float maxValue { get; set; }
}
public class StringAttr : Attribute
{
public string Value { get; set; }
public string Label { get; set; }
}
public class BoolAttr : Attribute
{
public bool Value { get; set; }
public string Label { get; set; }
}
MainWindow.xaml
<ListView x:Name="AssetList" ItemsSource="{Binding Attributes}" SelectionMode="Extended">
<ListBox.Resources>
<DataTemplate DataType="{x:Type model:IntAttr}">
<WrapPanel>
<TextBlock Text="{Binding Key}" Foreground="Blue"></TextBlock>
<TextBlock Text=" "></TextBlock>
<TextBlock Text="{Binding Value}"></TextBlock>
</WrapPanel>
</DataTemplate>
<DataTemplate DataType="{x:Type model:BoolAttr}">
<WrapPanel>
<TextBlock Text="{Binding Key}" Foreground="Red"></TextBlock>
<TextBlock Text=" "></TextBlock>
<TextBlock Text="{Binding Value}"></TextBlock>
</WrapPanel>
</DataTemplate>
</ListBox.Resources>
</ListView>
请您参考如下方法:
MVVM 方法是创建一个 ResourceDictionary
<ResourceDictionary .....>
<DataTemplate DataType="{x:Type Attribute}">
<views:AttributeView />
</DataTemplate>
<DataTemplate DataType="{x:Type FloatAttr }">
<views:FloatAttrView />
</DataTemplate>
<DataTemplate DataType="{x:Type IntAttr }">
<views:IntAttrView />
</DataTemplate>
当然每个类都有一个 View (用户控件)。然后你需要通过以下方式注册你创建的字典:
ResourceDictionary MyResourceDictionary = new ResourceDictionary();
MyResourceDictionary.Source = new Uri(ResourceDictionarypath, UriKind.Relative);
if ((Application.Current != null) && (Application.Current.Resources != null))
{
Application.Current.Resources.MergedDictionaries.Add(MyResourceDictionary);
}
或者,作为用户 Greg D建议,您可以使用分配给 ItemTemplateSelector 的简单数据模板选择器来分配正确的模板。如果您使用的映射比简单的 1:1 复杂一点,或者如果您有多个数据模板与同一底层 VM 相关联,这将很有用。
