我的组合框没有XAML,我想在后面的代码中添加一个带有值转换器的datatemplate,并将其附加到组合框。这是我现在的代码,它不起作用。它说它无法找到我的静态资源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。
答案 0 :(得分:1)
您需要将指向静态资源的链接(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>";