【问题标题】:How to set the DisplayMemberPath in a DataGrid?如何在 DataGrid 中设置 DisplayMemberPath?
【发布时间】:2013-01-21 06:12:20
【问题描述】:

我在 Wpf DataGrid 上苦苦挣扎。它的ItemsSource 是一个DataTable,其中由类型单元Tuple<int, string> 组成

这里有一些关于如何创建我的DataTable 的 sn-p 代码。

            // Create columns
            for (int j = 0; j < maxCount; j++) {
                dt.Columns.Add(selectedTests[i].Name + " " + (j + 1).ToString(), typeof(Tuple<int, string>));
            }

            // Create rows 
            for (int k = 0; k < tuple.Item2.Count; k++) {
                var newRow = dt.NewRow();
                dt.Rows.Add(newRow);
            }

            ...
            dt.Rows[k][i + m] = new Tuple<int, string>(n, str);

然后我将此DataTable 设置为我的DataGrid,并且我只想显示元组中的属性Item2,此时我需要保留元组实例。并且无法定义我的列来设置displaymemberPath,因为它是自动生成的。

    <DataGrid  x:Name="dataGrid" LoadingRow="dataGrid_LoadingRow_1" ItemsSource="{Binding DataTable}" DisplayMemberPath="{Binding Item2}">

我的数据网格一直转换成字符串我的元组是这样的:

【问题讨论】:

    标签: c# wpf xaml datagrid


    【解决方案1】:

    正如question 所说,您可以使用您的代码隐藏设置绑定。

    因此,您可以订阅 yourgrid_AutoGeneratingColumn 事件并执行以下操作:

    (e.Column as DataGridTextColumn).Binding = new Binding("Title");
    

    当然,您应该通过某些解决方案将 ColumnName 传递给 AutoGeneratingColumn 事件...

    【讨论】:

      【解决方案2】:

      您只需要手动设置列并将其绑定到 Item2 列。

      <DataGrid ItemsSource="{Binding DataTablePropertyInYourDataContext}">
      <DataGrid.Columns>
      <DataGridTextColumn 
                  Header="Item2" 
                  Binding="{Binding ColumnNameInYourDataTable}" 
                  />
      </DataGrid.Columns>
      </DataGrid>
      

      或另一种解决方法:您可以订阅 AutoGeneratingColumn 事件,当不需要的列等于 true 时设置取消。看看这个MSDN

      希望有帮助

      【讨论】:

      • 但我告诉你,我不是手动生成列,我真的不知道列数
      • 我不知道我是否收到您的问题。您能动态添加所需的 DataGrid 列及其绑定吗?
      • 是的,我是说,它们是使用AutoGenerateColumns datagrid 属性自动创建的
      • 更新了我的答案,请多解释一下你的目标,以防这不能解决你的问题。
      • 是的,我也在寻找那个事件,但我仍然无法完成。正如您在图像中看到的那样,我将Tuple&lt;int, string&gt; 设置为单元格,其中AutoGenerateColumns 属性设置为true。我正在寻找像DisplayMemberPath 这样的单元格。我的意思是在元组的数据网格中显示Item2,但包含当前值(元组..)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-03
      • 2011-07-20
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 2014-06-13
      相关资源
      最近更新 更多