简体   繁体   English

在用户控件内绑定WPF DataGrid

[英]Binding a WPF DataGrid inside a UserControl

I would like to create a UserControl containing a DataGrid and then define the columns directly inside my UserControl: 我想创建一个包含DataGrid的UserControl,然后直接在UserControl中定义列:

<my:ControlContainingDataGrid ItemsSource="{Binding}">
  <my:ControlContainingDataGrid.Columns>
    <DataGridTextColumn Binding="{Binding Path=Property1}" Header="Property 1"/>

In the UserControl I expose the columns of the DataGrid : 在UserControl中,我公开了DataGrid的列:

static ControlContainingDataGrid()
{
  ColumnsProperty = DependencyProperty.Register(
    "Columns",
    typeof(ObservableCollection<DataGridColumn>),
    typeof(ControlContainingDataGrid),
    new UIPropertyMetadata(new ObservableCollection<DataGridColumn>())
  );
}

[Description("Columns"), Category("Columns")]
public ObservableCollection<DataGridColumn> Columns
{
  get { return _datagGrid.Columns; }
}

public static readonly DependencyProperty ColumnsProperty;

=> it doesn't work : the column binded to Property1 is not created. =>它不起作用:未创建绑定到Property1的列。

I try to create the column programatically : 我尝试以编程方式创建列:

    _datagGrid.Columns.Add(new DataGridTextColumn {
      Header = "Property 1",
      Binding = new Binding {
        Path = new PropertyPath("Property1"),
        Mode = BindingMode.TwoWay,
      },
    });

_datagGrid.ItemsSource = testList;

=> it doesn't work : the header is displayed but each row of my DataGrid is empty (bad binding ?). =>它不起作用:显示标题,但我的DataGrid的每一行都是空的(绑定错误?)。


1- What is the simpliest way to bind the columns of a DataGrid via the UserControl in the XAML part ? 1-通过XAML部分中的UserControl绑定DataGrid列的最简单方法是什么?

2- What is the simpliest way to bind the columns of a DataGrid via the UserControl programatically ? 2-以编程方式通过UserControl绑定DataGrid列的最简单方法是什么?

I do this programmatically. 我以编程方式执行此操作。 Pretty much the same code as you have. 与您几乎相同的代码。 Works fine. 工作正常。 I have never tried to bind the Columns collection itself though I don't see why that should not work. 我从未尝试绑定Columns集合本身,尽管我不明白为什么这不起作用。

Your message is a little ambiguous. 您的信息有点含糊。 If you mean to say that your column does not show up, maybe you need to add the columns prior to creating the table. 如果您要说的是列未显示,则可能需要在创建表之前添加列。 If the rows show up with empty value in the column, then your binding 'Property1' is wrong. 如果行在列中显示为空值,则您的绑定“ Property1”是错误的。

I don't work in XAML so don't know nothing about that. 我不在XAML中工作,所以对此一无所知。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM