【问题标题】:binding ComboBox to DataGrid in the code在代码中将 ComboBox 绑定到 DataGrid
【发布时间】:2013-09-24 08:54:46
【问题描述】:

您好,我正在尝试在代码内的 DataGrid 中动态绑定 ComboBox。我看到了一些与此相关的答案,但没有一个有帮助。一般的意见是使用 DataTempleteColumn 但这也没有结果。这是我的代码

<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
    <Button Name="ButFill" Content="Fill Grid" HorizontalAlignment="Left" Height="22" Margin="373,65,0,0" VerticalAlignment="Top" Width="62"/>
    <DataGrid x:Name="DaGrid" HorizontalAlignment="Left" Height="134" Margin="25,38,0,0" VerticalAlignment="Top" Width="289" ItemsSource="{Binding}" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Header="text" Binding="{Binding Path=col1}"/>
            <DataGridComboBoxColumn Header="combobox" Width="105" ItemsSource="{Binding Path=fill_items}"/>
            <DataGridTemplateColumn Header="template combo" Width="105">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <ComboBox Name="TempCombo" ItemsSource="{Binding Path=fill_items}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>
</Grid>

而后面的代码是

Imports System.Collections.ObjectModel

Class MainWindow
    Public Property Table As New ObservableCollection(Of Test.dataset)()
    Public Property fill_items As New ObservableCollection(Of String)
    Private Sub ButFill_Click(sender As Object, e As RoutedEventArgs) Handles ButFill.Click
        Dim temp As New Test.dataset()
        Dim cb As New ComboBox
        fill_items.Add("ItemNo1")
        fill_items.Add("ItemNo2")
        cb.ItemsSource = fill_items
        temp.col1 = " Hello"
        temp.col2 = cb
        temp.col3 = cb
        Table.Add(temp)
        DaGrid.DataContext = Table
    End Sub
End Class


Public Class dataset
    Public Property col1 As String
    Public Property col2 As ComboBox
    Public Property col3 As ComboBox
End Class

我看到的问题是:

1) 在进入编辑模式之前,DataGridComboBox 列不会显示它。
2)两个组合框都是空的,但集合“表”似乎有一个 combobox.count 2。

我做错了吗? 有人可以给我看一个完整的绑定 ComboBox 的例子吗?

【问题讨论】:

    标签: wpf datagrid combobox


    【解决方案1】:

    fill_items 必须是 dataset 类中的公共属性,因为绑定在

                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <ComboBox Name="TempCombo" ItemsSource="{Binding Path=fill_items}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
    

    请参阅您绑定的集合中的每个项目。在您的情况下,它是 dataset 项目。

    您不能简单地使用 RelativeSource 或 ElementName 来查找 DataGrid 并绑定到它,因为 DataGridColumns 不会添加到可视化树中,因此这些绑定无法工作。

    【讨论】:

    • @FlorianGI,是的,这种方式有效,但问题是用户在组合框中进行选择后,我需要在代码中读回它。我无法读取所选项目,因为它通常在组合框或数据网格列中完成。我可以通过什么方式读回选择?
    • 在dataset 中创建一个属性,该属性应保存此值并将其绑定到 COMBOBOX 的 SelectedItem 属性 (Mode=TwoWay)。
    • @FlorianGI,这是&lt;ComboBox Name="TempCombo" ItemsSource="{Binding Path=fill_items}" SelectedItem="{Binding Path=items,Mode=TwoWay}"/&gt; 和数据集中的属性Public Property item As String 吗?如果是这样,那么它对我没有约束力
    • 绑定路径是items(末尾有一个s),但是你的属性叫做item。只是为了确定:将 UpdateSourceTrigger=PropertyChanged 添加到此绑定中。
    【解决方案2】:

    如果您想在 Window 的 DataContext 中的 combobox 中显示 fill_items,那么您需要更新您的 comboboxcolumn 绑定以使用 BindingProxy,因为 DataGrid 列不在 datagrid 的 Visualtree 中。

    <Window.Resources>
        <local:MyBindingProxy x:Key="myproxy" BindingData="{Binding}" />
    </Window.Resources>
    

    并且你必须在构造函数中将主窗口的 DataContext 设置为自身,例如 DataContext =this;

    那么您需要为 MyBindingProxy 编写类,例如:

    public class MyBindingProxy : Freezable
    {
        public static readonly DependencyProperty BindingDataProperty =
            DependencyProperty.Register("BindingData", typeof(object), 
            typeof(MyBindingProxy ), new UIPropertyMetadata(null));
    
        protected override Freezable CreateInstanceCore()
        {
            return new MyBindingProxy();
        }
    
        public object BindingData
        {
            get { return (object)GetValue(BindingDataProperty ); }
            set { SetValue(BindingDataProperty , value); }
        }
    
    }
    

    然后您可以将绑定更新为:

    <DataGridComboBoxColumn Header="combobox" Width="105" ItemsSource="{Binding BindingData.fill_items, Source={StaticResource myproxy}}"/>
    

    【讨论】:

    • 在调试模式下运行时仍然工作它给我一个错误。 System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.DataGrid', AncestorLevel='1''. BindingExpression:Path=fill_items; DataItem=null; target element is 'DataGridComboBoxColumn' (HashCode=58943162); target property is 'ItemsSource' (type 'IEnumerable')
    猜你喜欢
    • 2014-10-10
    • 1970-01-01
    • 2014-09-04
    • 2021-03-29
    • 2020-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多