【问题标题】:Create controltemplate in code, how to specify the converter in the binding在代码中创建controltemplate,如何在绑定中指定转换器
【发布时间】:2016-01-29 15:40:23
【问题描述】:

我检查了这些答案,但没有我想要的信息:
How to setup a WPF datatemplate in code for a treeview?
How to set Control Template in code?
Create ControlTemplate programmatically in WPF

这是我的代码的要点:

DataGridTextColumn col = new DataGridTextColumn();
Style styl = null;
//        Need to add this on a per-column basis
// <common:RequiredPropertyDisplayBrushConverter x:Key="requiredDisplayBrushConverter" />  
string xaml = "<ControlTemplate TargetType=\"{x:Type DataGridCell}\"> <TextBox Background=\"{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content.Text, Converter={StaticResource requiredDisplayBrushConverter}  > </TextBox> </ControlTemplate>";
MemoryStream sr = new MemoryStream(Encoding.ASCII.GetBytes(xaml));
ParserContext pc = new ParserContext();
pc.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
pc.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml");
ControlTemplate  ct = (ControlTemplate)XamlReader.Load(sr, pc);

styl.Setters.Add(new Setter(TemplateProperty, ct));
col.CellStyle = styl;  

在 ControlTemplate 中,绑定是指 cmets 中提到的转换器。当转换器在 xaml 中定义为 DataGrid 的资源时,我收到运行时错误:{“找不到名为 'requiredDisplayBrushConverter' 的资源。资源名称区分大小写。”}
我可以将此作为资源添加到列中吗?还是在运行时将其添加到 DataGrid 的资源中?
还是有其他的技巧?
谢谢--

【问题讨论】:

    标签: c# wpf controltemplate datagridcell


    【解决方案1】:

    您可以将其添加到 xaml,但您需要重新排列它。需要先定义资源,然后才能使用它。这意味着背景需要被定义为子标签。

    将您的 xaml 更改为:

    string xaml = "<ControlTemplate TargetType=\"{x:Type DataGridCell}\"><TextBox><TextBox.Resources><common:RequiredPropertyDisplayBrushConverter x:Key=\"requiredDisplayBrushConverter\" /></TextBox.Resources><TextBox.Background><Binding RelativeSource=\"{RelativeSource TemplatedParent}\" Path=\"Content.Text\" Converter=\"{StaticResource requiredDisplayBrushConverter}\"/></TextBox.Background></TextBox></ControlTemplate>";
    

    您需要定义公共命名空间。在您的其他命名空间之后添加它(当然,使用正确的命名空间/程序集):

    pc.XmlnsDictionary.Add("common", "clr-namespace:WPFApplication;assembly=WPFApplication");
    

    或者,如果可以的话,您可以只将资源添加到您的 App.xaml。

    【讨论】:

    • 谢谢!我完全忘记了将它添加到 app.xaml。我也很欣赏另一种解释。
    • 不客气。很高兴我添加了关于 app.xaml 的部分。我真的不认为它适用于你的情况。我不想问,但是……你能接受我的回答吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-17
    • 1970-01-01
    • 2017-10-29
    • 1970-01-01
    • 2011-01-27
    • 2013-02-23
    相关资源
    最近更新 更多