【问题标题】:WPF DataBinding - Changing ComboBox's SelectedItem not calling ViewModelWPF DataBinding - 更改 ComboBox 的 SelectedItem 不调用 ViewModel
【发布时间】:2011-04-27 01:39:09
【问题描述】:

以下代码未在我的视图模型中调用 SelectedItem 的属性设置器。

<ComboBox x:Name="cmbGuaranteeType"  Margin="5,5,5,5" MinWidth="80" 
          ItemsSource="{Binding Source={StaticResource guaranteeTypesKey}}" 
          SelectedItem="{Binding RelativeSource={RelativeSource AncestorType={x:Type wpfToolkit:DataGridRow}}, Path=DataContext.GuaranteeType, Mode=TwoWay}"
      />

视图是绑定到 ViewModel 的 UserControl。 UserControl 有一个 WpfToolkit 数据网格,它绑定到 ViewModel 上的 ObservableCollection。 ObservableCollection 由 List&lt;T&gt; 项组成。上面的组合框绑定到 T 项之一的“GuaranteeType”属性,如下所示:

public GuaranteeType? GuaranteeType
{
    get { return _guaranteeType; }
    set { _guaranteeType = value; NotifyPropertyChanged(ConstGuaranteeType); }
}

加载 UserControl 时,会调用 GuaranteeType 属性的 getter 并正确设置 SelectedItem。但是,当我单击 ComboBox 并尝试更改 SelectedItem 时,永远不会调用 GuarenteeType 属性的设置器。

此外,我在 XAML 中针对 View 的代码隐藏实现了 SelectionChanged="cmbGuaranteeType_SelectionChanged",当视图加载时,SelectionChanged 方法被调用一次,但当我在尝试更改组合框的选定项时释放鼠标时不会调用它。

【问题讨论】:

    标签: wpf data-binding


    【解决方案1】:

    对于如此含糊的回答,我深表歉意,但我以前见过这种情况,我似乎记得它与取消绑定 SelectedItem 的网格的单击事件有关。绑定单选按钮时也会发生类似的情况。

    对于组合框,我基本上总是默认使用 ListCollectionView 来公开底层的可观察集合并像这样设置 XAML:

    <ComboBox ItemsSource="{Binding ListCollectionViewPropertyHere}" IsSynchronizedWithCurrentItem="True"/>
    

    然后,如果您正在轮询,则可以从代码中获取 ListCollectionViewPropertyHere.CurrentItem,如果您需要在点击时收到通知,则可以订阅 ListCollectionViewPropertyHere.CurrentItemChanged 事件。

    【讨论】:

    • 在这种情况下轮询是什么意思?不过,我确实尝试了一些事情;我将 ItemsSource 更改为指向 ViewModel 上的 ListCollectionView 无济于事。在 ViewModel 中,我什至订阅了 CurrentChanging 和 CurrentChanged 事件,但它们仅在加载期间触发,而不是在更改时触发。令人惊讶的是,尽管 GuaranteeType 属性 getter 在绑定过程中返回了正确的 SelectedItem,但 ComboBox 并没有显示 SelectedItem(就像以前一样)。
    猜你喜欢
    • 2011-02-04
    • 1970-01-01
    • 1970-01-01
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    • 2012-06-19
    • 2016-06-15
    • 1970-01-01
    相关资源
    最近更新 更多