【问题标题】:Binding SelectedItem of ComboBox in DataGrid with different type用不同类型绑定 DataGrid 中 ComboBox 的 SelectedItem
【发布时间】:2013-05-22 16:33:35
【问题描述】:

我有一个包含 ComboBox 作为列的 DataGrid。

让我们考虑 DataGrid 有 ItemsSource 作为 ObservableCollection 和 ComboBox ItemsSource 是 List 。

我想根据 DataGrid ItemsSource 中的属性设置 ComboBox SelectedItem 属性。

但是 Product 类具有 int 类型的属性 ProductTypeId 而不是 ProductType。

那么我该如何设置 ComboBox SelectedItem 以便它显示 Product.ProductTypeId 的值作为选择。 而且我还想将 SelectedItems 与 Mode = TwoWay 绑定,这样每当 ComboBox SelectedItem 发生变化时,它就会反映在 DataGrid 的 ItemsSource 中。

任何帮助将不胜感激。

谢谢。

【问题讨论】:

    标签: wpf binding datagrid combobox datagridcomboboxcolumn


    【解决方案1】:

    DataGridComboBoxColumn 完全符合您的要求。要正确使用它,您需要了解以下属性:

    • SelectedValueBinding - 这是与您的对象/视图模型上的属性的绑定
    • SelectedValuePath - 这是ComboBox 内项目的值属性。当用户从ComboBox 中选择一个项目时,这将分配给您在SelectedValueBinding 中设置的属性。
    • DisplayMemberPath - 这是ComboBox 内项目的描述属性

    设置DataGridComboBoxColumnItemsSource 有点不同;请注意下面的示例,看看它是如何完成的。

    这些与标准的ComboBox 相同(SelectedValueBinding 除外)。

    以下是您的专栏的示例。

    <DataGridComboBoxColumn Header="Product Type" DisplayMemberPath="ProductType" SelectedValuePath="ProductTypeId" SelectedValueBinding="{Binding ProductTypeId, UpdateSourceTrigger=PropertyChanged}">
        <DataGridComboBoxColumn.ElementStyle>
            <Style TargetType="{x:Type ComboBox}">
                <Setter Property="ItemsSource" Value="{Binding AvailableProductTypes}"/>
                <Setter Property="VerticalAlignment" Value="Center"/>
            </Style>
        </DataGridComboBoxColumn.ElementStyle>
        <DataGridComboBoxColumn.EditingElementStyle>
            <Style TargetType="{x:Type ComboBox}">
                <Setter Property="ItemsSource" Value="{Binding AvailableProductTypes}"/>
                <Setter Property="VerticalAlignment" Value="Center"/>
            </Style>
        </DataGridComboBoxColumn.EditingElementStyle>
    </DataGridComboBoxColumn>
    

    【讨论】:

    • 那么如何使用 SelectedItemBinding?
    猜你喜欢
    • 2014-10-10
    • 2011-11-24
    • 1970-01-01
    • 2014-05-26
    • 2019-11-10
    • 2023-04-03
    • 2012-02-12
    • 2011-11-01
    • 1970-01-01
    相关资源
    最近更新 更多