开发者

How i set a DataTable to be the ItemsSource of a DataGridComboBoxColum?

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.

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.

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

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 开发者_StackOverflow社区= "Cities",
    SelectedValuePath = "ID",
    ItemsSource = test.Dt.DefaultView,
});

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; }
    }
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜