Silverlight数据模板与转换器代码后面
本文关键字:代码 转换器 数据 Silverlight | 更新日期: 2023-09-27 18:06:12
我的组合框没有XAML,我想在后面的代码中添加一个带值转换器的数据模板,并将其附加到组合框。这是我的代码,因为现在,它是不工作。它说它找不到我的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>";