通过名称绑定到静态资源

Binding to Static Resource via Name

我得到下一个模板:

<Page.Resources>
   <DataTemplate x:Key="T1">...</DataTemplate>
   <DataTemplate x:Key="T2">...</DataTemplate>
   <DataTemplate x:Key="T3">...</DataTemplate>
</Page.Resources>

和项目列表:

class SampleItem {
 ...
 public string ItemTemplateName { get; set; }
}

我梦想着以下一种方式使用它:

<ListView
   ItemTemplate = "{StaticResource {Binding ItemTemplateName}}">
</ListView> 

这样的事情可以做吗?这将是本案的正确绑定吗?

谢谢!

请尝试在这种情况下使用模板选择器。

XAML 页面资源变化

    <DataTemplate x:Key="T1">
        <Rectangle Fill="Tomato" Width="50" Height="50"></Rectangle>
    </DataTemplate>
    <DataTemplate x:Key="T2">
        <Rectangle Fill="Green" Width="50" Height="50"></Rectangle>
    </DataTemplate>
    <DataTemplate x:Key="T3">
        <Rectangle Fill="Blue" Width="50" Height="50"></Rectangle>
    </DataTemplate>
    <gridbackgroundProblemSoHelpAttempt:MyTemplateSelector x:Key="MyTemplateSelector" 
                                                           ADataTemplate="{StaticResource T1}"
                                                           BDataTemplate="{StaticResource T2}"
                                                           CDataTemplate="{StaticResource T3}"/>

Xaml ListView 更改(请注意 SampleItems 是 SampleItem 对象的 ObservableCollection)

<ListView ItemsSource="{Binding SampleItems}" ItemTemplateSelector="{StaticResource MyTemplateSelector}"/>

MyTemplateSelector 代码

 public class MyTemplateSelector : DataTemplateSelector
{
    public DataTemplate ADataTemplate { get; set; }
    public DataTemplate BDataTemplate { get; set; }
    public DataTemplate CDataTemplate { get; set; }

    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        var si = item as SampleItem;
        if (si == null) return null;
        var key = si.ItemTemplateName;

        switch (key)
        {
            case "A":
            {
                return ADataTemplate;
            }
                break;
            case "B":
            {
                return BDataTemplate;
            }
                break;
            case "C":
            {
                return CDataTemplate;
            }
                break;

            default:
                throw new ArgumentOutOfRangeException();
        }

    }
}

页面数据上下文

public class MainViewModel
{
    public MainViewModel()
    {
        SampleItems = new ObservableCollection<SampleItem>
        {
            new SampleItem{ItemTemplateName = "A"},
            new SampleItem{ItemTemplateName = "B"},
            new SampleItem{ItemTemplateName = "C"},

        };
    }
    public ObservableCollection<SampleItem> SampleItems { get; set; }
}

此致,