【问题标题】:access the Window's DataContext from within a DataGrid从 DataGrid 中访问 Window 的 DataContext
【发布时间】:2011-03-24 21:09:46
【问题描述】:

我在从 DataGrid 中访问 Window 的 DataContext 时遇到了一些问题。

DataGrid 绑定到一个 IBindingList:

public IBindingList Items{ get; set; }
    private void initItems()
    {
        //ItemFactory is a Linq2SQL Context, Items is the view of availabe Items
        this.Items = this.ItemFactory.Items.GetNewBindingList();
    }

我尝试从我的 xaml 中获取这些数据以填充 ComboBox:

 <DataGridComboBoxColumn Header="Typ" 
                             DisplayMemberPath="Description"
                             SelectedValuePath="ItemID"      
                             ItemsSource="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}, Mode=OneWay, Path=DataContext.Items, UpdateSourceTrigger=PropertyChanged}" />

但它不起作用。我已经尝试了很多变种。组合框未填充。
非常感谢任何帮助!

注意:

同一窗口中的以下 ComboBox 确实有效:

<ComboBox x:Name="workingCombo" ItemsSource="{Binding Path=Items}" DisplayMemberPath="Description" SelectedValuePath="ItemID" />

【问题讨论】:

    标签: wpf data-binding binding datagridcomboboxcolumn


    【解决方案1】:

    DataGridComboBoxColumn 没有直接连接到可视化树,因此FindAncestor 操作将失败(并且 DataContext 也不会被继承)。

    • 最简单的解决方案是 为每一行创建一个 ViewModel 并在 ItemsSource 中提供 用于组合框。
    • 使用DataGridTemplateColumn 并将ComboBox 放在 DataTemplate 有帮助。
    • Here 是关于这个问题的另一篇文章。并查看this 发布。

    【讨论】:

    • 感谢您的回答!我没有通过谷歌搜索找到这两个帖子。 - 为每一行使用 ViewModel 的问题是我将 BindingList 直接绑定到 DataGrid 的 ItemSource。 - 如果我必须使用 DataGridTemplateColumn .. DataGridComboBoxColumn 的价值是什么?..猜猜只能将它与静态定义的集合一起使用。明天我会在工作中尝试一下,然后当我成功时将其标记为答案;)再次
    • 当我在 DataGridTemplateColumn 中使用 ComboBox 时,它使用 RelativePath 起作用
    • 我知道答案已经快 10 年了,但是第二个链接已经失效了。
    猜你喜欢
    • 2016-01-19
    • 2012-06-29
    • 1970-01-01
    • 2016-10-04
    • 2011-01-26
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多