为WPF用户控件datagrid创建属性

时间:2016-03-01 17:32:49

标签: wpf user-controls

我有一个名为IGrid的数据网格的用户控件。我想为它添加GridViewColumnCollection poperty。

public class DataGridNumericColumn : DataGridTextColumn
{
    protected override object PrepareCellForEdit(System.Windows.FrameworkElement editingElement, System.Windows.RoutedEventArgs editingEventArgs)
    {
        TextBox edit = editingElement as TextBox;
        edit.PreviewTextInput += OnPreviewTextInput;
        return base.PrepareCellForEdit(editingElement, editingEventArgs);
    }
    void OnPreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
    {
        try
        {
            Convert.ToInt32(e.Text);
        }
        catch
        {
            e.Handled = true;
        }
    }
}

从谷歌我得到了一段代码`

private Collection<DataGridColumn> field = new Collection<DataGridColumn>();
[Category("Data")]
[Description("Column Creation")]                     
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public Collection<DataGridColumn> Columns
{
    get { return field; }
}

这里我可以在可视化树中获取GridViewColumnCollection, 我的问题是如何使用上面的代码在集合中添加新类型(DataGridNumericColumn)。

enter image description here

1 个答案:

答案 0 :(得分:0)

如果您不知道代码的作用,最好在尝试使用它或提出自己的解决方案之前对其进行研究。据我所知,您正在尝试向继承DataGrid的UserControl添加其他属性。

您有两种选择:

  1. 创建一个DependencyProperty(在我看来是最好的选择)。
  2. 创建普通属性
  3. 以下是一些帮助您入门的链接:

    What is the difference between Property and Dependency Property

    When should I use dependency properties in WPF?

相关问题