使用code仅次于添加按钮,动态生成的WPF DataGrid列的标题 [英] Using code behind only add button to dynamically generated WPF DataGrid column's header

查看:164
本文介绍了使用code仅次于添加按钮,动态生成的WPF DataGrid列的标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有了它在code动态生成列的WPF DataGrid和我需要插入每个列的标题小按钮的文字来实现在弹出的对话框中自定义的(复杂)过滤的权利。

I have a wpf datagrid that has it's columns generated dynamically in code and I need to insert small buttons in each column's header to the right of the text to implement custom (complex) filtering in a popup dialog.

我在遇到麻烦找出如何插入一个按钮到只使用code后面的DataGrid列标题。

I'm having trouble figuring out how to insert a button into a datagrid column header using only code behind.

这是我开始沿着走的路线(注释掉位),但它不工作:

This is the route I started going down (commented out bit) but it doesn't work:

private static DataGridTextColumn GetTextColumn(string ColumnName, string FormatString, bool AlignRight)
       {
           DataGridTextColumn c = new DataGridTextColumn();
           c.Header = Test.Common.UIBizObjectCache.LocalizedText.GetLocalizedText(ColumnName);
           c.Binding = new System.Windows.Data.Binding(ColumnName);
           if (!string.IsNullOrWhiteSpace(FormatString))
               c.Binding.StringFormat = FormatString;
           if (AlignRight)
           {
               Style cellRightAlignedStyle = new Style(typeof(DataGridCell));
               cellRightAlignedStyle.Setters.Add(new Setter(DataGridCell.HorizontalAlignmentProperty, HorizontalAlignment.Right));
               c.CellStyle = cellRightAlignedStyle;
           }

           //var buttonTemplate = new FrameworkElementFactory(typeof(Button));
           //buttonTemplate.Text = "X";
           //buttonTemplate.AddHandler(
           //                   Button.ClickEvent,
           //                   new RoutedEventHandler((o, e) => HandleColumnHeaderButtonClick(o, e))
           //               );
           //c.HeaderTemplate=new DataTemplate(){VisualTree = buttonTemplate};

           return c;
       }

我得到一个InvalidOperationException'内容presenter类型必须实现IAddChild在FrameworkElementFactory的appendChild使用。

I get an invalidoperationexception "'ContentPresenter' type must implement IAddChild to be used in FrameworkElementFactory AppendChild."

显然,我做错了。 :)任何帮助将大大AP preciated。

Clearly I'm doing it wrong. :) Any help would be greatly appreciated.

推荐答案

你需要使用模板?如果没有使用普通的 标题 属性:

Do you need to use a template? If not use the normal Header property:

string colProperty = "Name";

DataGridTextColumn col = new DataGridTextColumn();
col.Binding = new Binding(colProperty);
var spHeader = new StackPanel() { Orientation = Orientation.Horizontal };
spHeader.Children.Add(new TextBlock(new Run(colProperty)));
var button = new Button();
button.Click += Button_Filter_Click;
button.Content = "Filter";
spHeader.Children.Add(button);
col.Header = spHeader;

dataGrid.Columns.Add(col);

这篇关于使用code仅次于添加按钮,动态生成的WPF DataGrid列的标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆