在代码中创建controltemplate,如何在绑定中指定转换器

时间:2016-01-27 17:01:06

标签: c# wpf controltemplate datagridcell

我检查了这些答案,但没有人得到我正在寻找的信息:
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中,绑定是指注释中提到的转换器。当转换器在xaml中定义为DataGrid的资源时,我收到运行时错误:{“找不到名为'requiredDisplayBrushConverter'的资源。资源名称区分大小写。”}
我可以将此作为资源添加到列中吗?或者在运行时将它添加到DataGrid的资源中? 还是有其他技术?
谢谢 -

1 个答案:

答案 0 :(得分: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中,如果这是一个选项。

相关问题