【发布时间】: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