【问题标题】:wpf dataGrid binding selecteditem not workingwpf dataGrid绑定选定项不起作用
【发布时间】:2012-12-16 17:07:22
【问题描述】:

我正在尝试将数据网格的 selectedItem 与 MVVM 中的属性绑定。 问题是它不会触发属性的“Set”。

在我拥有的 xaml 部分:

 <WPFCtrlDg:ExtDataGrid Name="_edgMessage" Grid.Row="1" 
      ItemsSource="{Binding Path=LNE_MESSAGE, Mode=OneWay}"
      SelectedItem="{Binding Path=CurrentMessage, Mode=TwoWay}">

在代码部分:

 private LNE_MESSAGE _currentMessage;
    public LNE_MESSAGE CurrentMessage
    {
        get
        {
            if (_currentMessage == null)
            {
                ICollectionView collectionView = CollectionViewSource.GetDefaultView(LNE_MESSAGE);
                if (collectionView != null)
                    return collectionView.CurrentItem as LNE_MESSAGE;
                return null;
            }
            return _currentMessage;
        }
        set
        {
            ICollectionView collectionView = CollectionViewSource.GetDefaultView(LNE_MESSAGE);
            if (collectionView != null)
                collectionView.MoveCurrentTo(value);

            _currentMessage = value;
            OnPropertyChanged(() => CurrentMessage);
        }
    }

extdatagrid 是一个自定义控件,并且 selected item 属性是这样完成的:

        public object SelectedItem
    {
        get { return GetValue(SelectedItemProperty); }
        set { SetValue(SelectedItemProperty, value); }
    }

    public static readonly DependencyProperty SelectedItemProperty =
        DependencyProperty.Register("SelectedItem", typeof(object), typeof(ExtDataGrid),
                                new UIPropertyMetadata((s, e) => 
                                                                {
                                                                    ExtDataGrid extDg = s as ExtDataGrid;
                                                                    Debug.Assert(extDg != null);
                                                                    extDg.CurrentItem = e.NewValue;
                                                                }));

知道如何正确绑定 selecteditem 属性吗?

【问题讨论】:

    标签: wpf mvvm binding datagrid selecteditem


    【解决方案1】:

    检查您的数据上下文是否设置正确。 并调试并查看本地窗口以查看数据上下文是否实际上是使用可视化助手设置的。另请参阅输出窗口以了解任何绑定错误。

    乍一看,你的依赖属性看起来是对的。

    【讨论】:

    • 调试时可以查看参数的本地窗口,请参阅此 => blogs.msdn.com/b/zainnab/archive/2010/01/29/…
    • 两个窗口都是空的(不知道我是否需要在输出上打印一些东西)。顺便说一句,datagrid 使用与 CurrentMessage 位于同一视图模型中的 LNE_MESSAGE 属性正确加载其内容,所以我认为 datacontext 是正确的
    • CurrentMessage 始终设置为数据网格中的第一项,即使选择更改也不会更改
    • 调试你的依赖属性,看看它是否进入集合
    • 不,它没有。它只是在加载数据网格时注册依赖属性,但它从不进入get或set方法
    猜你喜欢
    • 1970-01-01
    • 2018-07-27
    • 1970-01-01
    • 1970-01-01
    • 2015-06-16
    • 2011-02-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    相关资源
    最近更新 更多