我正在实现一个 UserControl ,它应该显示设置列表:
public class SettingPropertyItem {
string Name { get; }
Type ValueType { get; }
object Value { get; set; }
}
基于每种类型ValueType
应使用不同的 DataTemplate。
为了促进这一点,用户控件具有以下控件,其中包含SettingPropertyItem
作为其数据上下文:
<UserControl x:Class="AVDump3Gui.Controls.Settings.SettingsView">
...
<ItemsControl Items="{Binding Properties}" Margin="16,0,0,0">
<ItemsControl.ItemTemplate>
<DataTemplate>
...
<ContentControl Content="{Binding}"/>
...
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
...
</UserControl>
然后在使用 Usercontrol 的视图中,我在其 DataTemplates 中添加了一个 DataTemplate:
<sv:SettingsView.DataTemplates>
<DataTemplate DataType="{x:Type vm:SettingPropertyItem}">
...
</DataTemplate>
</sv:SettingsView.DataTemplates>
到目前为止一切顺利,一切都按预期进行。但现在我有点困惑,因为我不知道如何基于 DataContext 中的属性应用不同的 DataTemplate。
对于 WPF,DataTemplateSelector 或触发器似乎是可行的方法(忽略其他框架),但它们在 Avalonia 中似乎不存在。我也尝试过样式,但选择器似乎无法访问 DataContext 属性。
如何才能做到这一点?
位于阿瓦罗尼亚DataTemplateSelector
不需要,因为你可以实施IDataTemplate
您自己并选择那里的模板。
i. e.
public class MyTemplateSelector : IDataTemplate
{
public bool SupportsRecycling => false;
[Content]
public Dictionary<string, IDataTemplate> Templates {get;} = new Dictionary<string, IDataTemplate>();
public IControl Build(object data)
{
return Templates[((MyModel) data).Value].Build(data);
}
public bool Match(object data)
{
return data is MyModel;
}
}
public class MyModel
{
public string Value { get; set; }
}
<ItemsControl>
<ItemsControl.Items>
<scg:List x:TypeArguments="local:MyModel">
<local:MyModel Value="MyKey"/>
<local:MyModel Value="MyKey2"/>
</scg:List>
</ItemsControl.Items>
<ItemsControl.DataTemplates>
<local:MyTemplateSelector>
<DataTemplate x:Key="MyKey">
<TextBlock Background="Red" Text="{Binding Value}"/>
</DataTemplate>
<DataTemplate x:Key="MyKey2">
<TextBlock Background="Blue" Text="{Binding Value}"/>
</DataTemplate>
</local:MyTemplateSelector>
</ItemsControl.DataTemplates>
</ItemsControl>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)