繁体   English   中英

Silverlight Datatemplate,后面有转换器代码

[英]Silverlight Datatemplate with converter code behind

我的组合框没有XAML,我想在后面的代码中添加一个带有值转换器的datatemplate并将其附加到组合框。 这是我到目前为止的代码,它不起作用。 它说找不到我的staticresource SelectableColorConverter

        this.Resources.Add("SelectableColorConverter", new SelectableColorConverter());
        string template = "<DataTemplate xmlns=\"http://schemas.microsoft.com/client/2007\"><TextBlock Text=\"{Binding}\" Foreground=\"{Binding Converter={StaticResource SelectableColorConverter}}\" /></DataTemplate>";
        DataTemplate dt = XamlReader.Load(template) as DataTemplate;
        this.ItemTemplate = dt;
    }

任何帮助,将不胜感激。 SelectableColorConverter是一个IValueConverter。

您需要通过以下方式将指向静态资源(SelectableColorConverter)的链接添加到您的DataTemplate中:

string template = "<DataTemplate xmlns=\"http://schemas.microsoft.com/client/2007\"";
templete += "xmlns:local=\"clr-namespace:NamespadeName; assembly=AssemblyName\">"
template += "<DataTemplate.Resources> <local:SelectableColorConverter x:Key=\"colorConverter\"/>";
template += "</DataTemplate.Resources>";
template += "<TextBlock Text=\"{Binding}\" Foreground=\"{Binding ., Converter={StaticResource ResourceKey=colorConverter}}\" />";
template += "</DataTemplate>";

将SelectableColorConverter添加到App.xaml中的资源中:

<Application
x:Class="Test.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:convertor="using:Test.Converters"
xmlns:local="using:Test">

<Application.Resources>
    <convertor:SelectableColorConverter x:Key="SelectableColorConverter"/>
</Application.Resources>
</Application>

然后

string template = "<DataTemplate xmlns=\"http://schemas.microsoft.com/client/2007\">";
template += "<TextBlock Text=\"{Binding}\" Foreground=\"{Binding ., Converter={StaticResource SelectableColorConverter}}\" />";
template += "</DataTemplate>";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM