c# - 在 Avalonia 中根据 DataContext 属性选择 DataTemplate

标签 c# datatemplate datatemplateselector avaloniaui

我正在实现一个应该显示设置列表的 UserControl:

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

应根据 ValueType 中的每种类型使用不同的 DataTemplate。
为方便起见,UserControl 具有以下控件,其中 SettingPropertyItem 作为其 DataContext:

<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 的 View 中,我在其 DataTemplates 中添加了一个 DataTemplate:

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

到目前为止一切顺利,一切正常。但现在我有点难过,因为我不知道如何根据 DataContext 中的属性应用不同的 DataTemplate。
使用 WPF,DataTemplateSelector 或 Triggers 似乎是要走的路(忽略其他框架),但它们似乎在 Avalonia 中不存在。我也尝试过样式,但选择器似乎无法访问 DataContext 属性。

如何做到这一点?

最佳答案

在 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>

关于c# - 在 Avalonia 中根据 DataContext 属性选择 DataTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63207058/

相关文章:

c# - 匹配包含未知文本的字符串

c# - 带有 ListView 的数据绑定(bind) WPF TabControl 导致滚动问题

.net - 如何将 StringFormat 添加到 DataTemplate 内的 Textblock?

c# - 每个单元格中具有不同 UserControl 的 WPF DataGrid

xamarin.ios - Xamarin 使用 DataTemplate 形成 UICollectionView

c# - ActionFilterAttribute 中的 GetService 返回 null

c# - 在 Windows C++ 或 C# 中,您可以询问操作系统当前是否正在关闭/重新启动/注销

c# - 通用参数推断和不明确的函数调用 - 有解决方法吗?

c# - 在代码中获取 DynamicResource

c# - 在用户控件 WPF 中使用数据模板选择器时抛出空引用异常