我如何将 DataTable 设置为 DataGridComboBoxColum 的 ItemsSource? [英] How i set a DataTable to be the ItemsSource of a DataGridComboBoxColum?

查看:21
本文介绍了我如何将 DataTable 设置为 DataGridComboBoxColum 的 ItemsSource?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含两列的数据表,我将绑定到 DataGridComboBoxColumn 的所有组合框,其中一列将是项目的文本,其他将是项目的值.

I have a DataTable with two Columns that i will bind to all the ComboBoxes of a DataGridComboBoxColumn where one of the Columns will be the Text of the Items, and other will be the Values of the Items.

我知道名为DisplayMemberPath"的属性是我将列的名称指定为项目文本的地方,以及必须在SelectedValuePath"属性中指定的值.

I know that the property called 'DisplayMemberPath' is where i specify the Name of the Column to be the Text of the Items, and to the values it have to be specified in the 'SelectedValuePath' property.

但是再一次将任何内容绑定到 DataGridComboBoxColumn 是一个问题,因为它无法访问 DataGrid 的 DataContext.

But one more time it's a problem to Bind whatever to a DataGridComboBoxColumn because it can't access the DataContext of the DataGrid.

那么我如何将 DataTable 设置为 DataGridComboBoxColum 的 ItemsSource?

So how i set a DataTable to be the ItemsSource of a DataGridComboBoxColum?

我想要在代码隐藏中起作用的示例:

Example where what i want works in Code Behind:

TestClass test = new TestClass();

dataGrid.Columns.Add(new DataGridComboBoxColumn()
{
    Header = "City",
    DisplayMemberPath = "Cities",
    SelectedValuePath = "ID",
    ItemsSource = test.Dt.DefaultView,
});

这是我的 XAML 代码:

Here is my XAML Code:

<Window x:Class="WpfApp3.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApp3
    Title="MainWindow" Height="350" Width="600">

    <Grid Name="grid1">
        <DataGrid Name="dataGrid" AutoGenerateColumns="False" MinColumnWidth="100">
            <DataGrid.Columns>
                <DataGridComboBoxColumn Header="City" DisplayMemberPath="Cities" SelectedValuePath="ID" ItemsSource="{Binding local:TestClass.Dt}"/>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

这是我的代码隐藏代码:

Here is my Code Behind code:

public class TestClass
{
    public TestClass()
    {
        (...)
        //Here i am loading my DataTable
    }

    private static DataTable dt;

    public static DataTable Dt
    {
        get { return dt; }
    }
}

推荐答案

要么,
A. 将 ComboBox 的 DataContext 显式设置为您的 DataTable,或者
B. 如果 DataTable 是您绑定到 DataGrid 的对象的某个部分,请在 ComboBox 绑定中使用 RelativeSource.

Either,
A. explicity set the DataContext of ComboBox to your DataTable, OR
B. if DataTable is some part of the object that you have bound to the DataGrid, use RelativeSource in ComboBox binding.

如果您需要针对这些场景的具体帮助,则需要发布您的代码.

You will need to post your code, if you need specific help for these scenarios.

这篇关于我如何将 DataTable 设置为 DataGridComboBoxColum 的 ItemsSource?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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