大家下午好,
我们的 WPF 应用程序 (VS 2010) 上有一个 XamDataGrid,我需要以编程方式为一个字段添加控件模板(字段始终从我们应用程序上的代码添加)。
因此,我不是在 XAML 上创建模板,而是从代码创建它(我关注了几篇解释类似问题的帖子),如下所示:
Field f = new Field { Name = name, Label = label, Width = new FieldLength(20) };
Style cellStyle = new System.Windows.Style();
string templateStr = "<ControlTemplate TargetType="{x:Type igDP:CellValuePresenter}">" +
"<Button Content="Flu" />" +
"</ControlTemplate>";
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");
pc.XmlnsDictionary.Add("igDP", "http://infragistics.com/DataPresenter");
ControlTemplate ct = (ControlTemplate)XamlReader.Parse(templateStr, pc);
cellStyle.Setters.Add(new Setter() { Property = CellValuePresenter.TemplateProperty, Value = ((object)new CellValuePresenter() { Template = ct }) });
f.Settings.CellValuePresenterStyle = cellStyle;
MainDataGrid.FieldLayouts[0].Fields.Add(f);
不知何故,这不起作用,我的字段/列都没有显示。所以这是行不通的,任何帮助将不胜感激。
好的!我找到了!
问题是我将资源库添加到控件模板的方式,因此而不是:
cellStyle.Setters.Add(new Setter() { Property = CellValuePresenter.TemplateProperty, Value = ((object)new CellValuePresenter() { Template = ct }) });
它应该是这样的:
cellStyle.Setters.Add(new Setter(CellValuePresenter.TemplateProperty, ct));
然后它起作用了!
我知道这不是最好的方法,但这就是我被要求这样做的方式。