【问题标题】:How i set a DataTable to be the ItemsSource of a DataGridComboBoxColum?我如何将 DataTable 设置为 DataGridComboBoxColum 的 ItemsSource?
【发布时间】:2011-07-25 14:01:39
【问题描述】:

我有一个包含两列的 DataTable,我将绑定到 DataGridComboBoxColumn 的所有 ComboBoxes,其中一列是项目的文本,另一列是项目的值。

我知道名为“DisplayMemberPath”的属性是我将列的名称指定为项目的文本的地方,并且必须在“SelectedValuePath”属性中指定它的值。

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

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

我想要的代码在后面的工作示例:

TestClass test = new TestClass();

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

这是我的 XAML 代码:

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

这是我的代码背后的代码:

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

    private static DataTable dt;

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

【问题讨论】:

标签: wpf binding wpfdatagrid


【解决方案1】:

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

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

【讨论】:

  • 如果对您有帮助,我将发布我想做的代码示例。但我想要的是在我的 XAML 中访问代码隐藏中的 DataTable。我只需要一种方法或了解如何去做。我知道如何使用静态资源,但如果不是静态资源并且此 DataTable 不能是,我不知道也无法理解如何操作。
  • 代码会有所帮助,否则我们将继续做出假设。
  • 我已经发布了代码,以便更准确地表达我的需要。 Code behind 中的示例可以正常工作并执行我需要的操作,但我想在 XAML 中执行此操作。
  • 那么这似乎是相关的:Problem binding to static property
猜你喜欢
  • 2021-11-03
  • 1970-01-01
  • 1970-01-01
  • 2020-06-29
  • 2010-10-04
  • 2016-10-13
  • 2011-09-01
  • 2010-12-21
  • 1970-01-01
相关资源
最近更新 更多