通过名称绑定到静态资源

时间:2016-02-01 13:37:03

标签: wpf windows-phone-8 binding itemtemplate staticresource

我得到下一个模板:

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

这可能会做那样的事吗?对于这种情况,这将是正确的约束吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

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

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();
        }

    }
}

Page DataContext

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; }
}

此致