在Avalonia中根据DataContext属性选择一个DataTemplate

4

我正在实现一个用户控件,它应该显示一系列设置:

public class SettingPropertyItem {
    string Name { get; }
    Type ValueType { get; }
    object Value { get; set; }
}

根据ValueType中的每个类型,应使用不同的DataTemplate。
为了方便起见,用户控件具有以下控件,其DataContext为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的视图中,我添加了一个DataTemplate到其DataTemplates中:

<sv:SettingsView.DataTemplates>
  <DataTemplate DataType="{x:Type vm:SettingPropertyItem}">
    ...
  </DataTemplate>
</sv:SettingsView.DataTemplates>

到目前为止,一切都很顺利,一切都按预期运行。但是现在我有点困惑,因为我不知道如何根据DataContext中的属性应用不同的DataTemplates。在WPF中,DataTemplateSelector或Triggers似乎是可行的方法(忽略其他框架),但它们似乎在Avalonia中不存在。我还尝试使用样式,但选择器似乎无法访问DataContext属性。

该怎么做?

1个回答

10
在Avalonia中,不需要使用DataTemplateSelector,因为您可以自己实现IDataTemplate并在那里选择模板。例如:
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>

谢谢,这正是我在寻找的。 - Arokh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接