且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-30 09:35:22

在Avalonia中不需要 DataTemplateSelector ,因为您可以自己实现 IDataTemplate 并在其中选择模板

In Avalonia DataTemplateSelector isn't needed because you can just implement IDataTemplate yourself and select the template there.

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>