0

大家下午好,

我们的 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); 

不知何故,这不起作用,我的任何字段/列都没有显示。所以这不起作用,任何帮助将不胜感激。

4

1 回答 1

0

好的!我找到了!

问题是我将设置器添加到 ControlTemplate 的方式,所以不是:

cellStyle.Setters.Add(new Setter() { Property = CellValuePresenter.TemplateProperty, Value = ((object)new CellValuePresenter() { Template = ct }) });

它应该是这样的:

cellStyle.Setters.Add(new Setter(CellValuePresenter.TemplateProperty, ct));

然后它起作用了!

我知道这不是最好的方法,但这就是我被要求这样做的方式。

于 2013-11-07T14:06:08.273 回答