【问题标题】:Silverlight Datatemplate with converter code behind带有转换器代码的 Silverlight 数据模板
【发布时间】:2014-07-22 21:35:48
【问题描述】:

我的组合框没有 XAML,我想在后面的代码中添加一个带有值转换器的数据模板并将其附加到组合框。这是我现在的代码,它不起作用。它说它找不到我的静态资源 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。

【问题讨论】:

  • 你想完成什么?
  • 最终让组合框中的项目根据转换器中的规则更改颜色。组合框不能使用组合框项,因此不能一次将模板应用于每个项目。我相信应用项目模板是解决此问题的唯一方法,但您似乎无法严格从代码隐藏中附加一个带有转换器的模板。
  • 不同的物品有不同的颜色吗?还是一次只对所有项目应用一种颜色,以便所有项目都统一着色?

标签: c# silverlight code-behind


【解决方案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>";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 2012-01-20
    • 2011-01-31
    • 2011-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多