Datagrid自定义组合框不更新

时间:2014-03-24 14:10:25

标签: wpf binding wpfdatagrid

我遇到了WPF Datagrid的DataGridTemplateColumn问题,并根据用户的交互更新了ComboBox上显示的项目。由于程序是数据库绑定的,因此从数据库中立即加载所有项目是没有意义的,而是使用实体框架来提取用户在给定时刻请求的内容。

为了方便视图的紧凑,下一个/上一个按钮位于组合框模板上,以及搜索功能,我遇到的问题是: 当模板化的组合框位于数据网格中时,next / previous不起作用。在数据网格之外,它们可以正常运行。

我甚至尝试使用Combobox存在的知识,并通过按名称搜索该组合框手动将其从可视树中拉出,拉出其对itemssource的绑定并告诉它更新。没有任何事情发生。

以下是我的意思: enter image description here

选择新单元格后,显示屏会更新;但是,因为我捕获它即将进入编辑模式并更新列表以包含所选项目(为了绑定目的,ComboBox不希望有一个选定的项目不在其中项目集。)

你可以想象,这是一个相当大的问题。在找到解决方案之前,很难继续开发此功能。这是Datagrids的已知问题吗?如果是这样,我可能不得不自己动手。由于性能原因我不想这样做,我不是MVVM专家,UI看起来唯一的原因就是它本身就是在定义自己。

1 个答案:

答案 0 :(得分:0)

我很愚蠢,这就是问题所在:

private static void UpdateComboDropdown(string comboboxName, DataGrid dataGrid)
{
    /* *
     * I think CurrentItem is used in this instance because 
     * it's a single cell selection mode?
     * *
     * I CBA to check.
     * */
    var selectedRow = dataGrid.ItemContainerGenerator.ContainerFromItem(dataGrid.CurrentItem) as DataGridRow;
    if (selectedRow != null)
    {
        DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(selectedRow);
        if (presenter != null)
        {

            var visualComboBox = presenter.FindChild<ComboBox>(comboboxName);
            if (visualComboBox != null)
            {
                var binding = visualComboBox.GetBindingExpression(ComboBox.ItemsSourceProperty);
                if (binding != null)
                    binding.UpdateTarget();
            }
            var popupPart = visualComboBox.FindChild<Popup>("PART_Popup");
            if (popupPart != null && popupPart.Child != null)
            {
                //Popup has one child, reports zero children, so: search on its child.
                var previous = popupPart.Child.FindChild<Button>("PreviousButton");
                if (previous != null)
                {
                    var previousIsEnabledBinding = previous.GetBindingExpression(Button.IsEnabledProperty);
                    if (previousIsEnabledBinding != null)
                        previousIsEnabledBinding.UpdateTarget();
                }
                var next = popupPart.Child.FindChild<Button>("NextButton");
                if (next != null)
                {
                    var nextIsEnabledBinding = next.GetBindingExpression(Button.IsEnabledProperty);
                    if (nextIsEnabledBinding != null)
                        nextIsEnabledBinding.UpdateTarget();
                }
            }
        };
    }
}

我告诉它更新组合框的ItemsSource,而不是相反。至于为何关系不会自动更新,我不知道。现在,了解如何在其下拉列表中更新组合框控件的组成元素。可能会涉及获取其PART_Popup,然后是下一个/上一个按钮及其各自的绑定。这很烦人。

编辑:使用完整解决方案更新了答案。