c# - 绑定(bind)到 WPF 组合框的 'SelectedItem' 的属性的奇怪行为

标签 c# wpf mvvm combobox

将属性绑定(bind)到 SelectedItem 时对于 WPF 组合框,我希望每次组合框的选择发生更改时都会调用该属性 setter 。我没有看到。

组合框是否应该调用绑定(bind) SelectedItem更改选择时的属性 setter ?

加法 :我实际上在那里有部分绑定(bind):当第一次加载/选择组合框时,属性 getter 被调用,属性 setter 被调用一次,并且在以后的选择更改时不再调用。

我注意到的一件事是,当我把 IsSynchronizedWithCurrentItem = True在 Xaml 的组合框条目中,setter 在组合框加载/初始选择时被调用一次,但再也不会调用。当我删除该组合框属性时,setter 永远不会被调用。很奇怪。

另外,我指的是 View 模型属性,而不是依赖属性。至少我没有将它设置为依赖属性。我对此很陌生(惊喜!),所以关于这个主题的更多信息将不胜感激。

xml代码:

<ComboBox MinWidth="300" Margin="5,0,0,5"
   ItemsSource="{Binding KeywordCollectionTypes, Mode=OneWay}"
   SelectedItem="{Binding KeywordCollectionType, Mode=TwoWay}"
   IsSynchronizedWithCurrentItem="True"/>

ViewModel 代码(绑定(bind)的属性):
 public Collection<string> KeywordCollectionTypes
    {
        get
        {
            return _KeywordCollectionTypes;
        }
    }

public string KeywordCollectionType
    {
        get
        {
            return _KeywordCollectionType;
        }
        set
        {
            _KeywordCollectionType = value;

            OnPropertyChanged("KeywordCollectionType");
        }
    }

还有一点信息是组合框在 DataGrid.RowDetailsTemplate 内。 ,那么这种奇怪的更新行为是否与它在行详细信息中有关?

最佳答案

我终于弄清楚了我遇到的问题。在组合框的 SelectedItem 的绑定(bind)语句中,我需要输入:“UpdateSourceTrigger=PropertyChanged”

像这样:

<ComboBox MinWidth="300" Margin="5,0,0,5"
                                      ItemsSource="{Binding KeywordCollectionTypes, Mode=OneWay}"
                                      SelectedItem="{Binding KeywordCollectionType, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

这是让我解决问题的线程:

Problem with data binding (Using the MVVM pattern) to a WPF Combobox within a DataGrid's RowDetailsTemplate

关于c# - 绑定(bind)到 WPF 组合框的 'SelectedItem' 的属性的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3198743/

相关文章:

c# - 高级 HTML Agility Pack 使用

c# - Process.start:如何获得输出?

WPF 数据绑定(bind)必应 map wpf api

c# - 父对象的 WPF 中的数据绑定(bind)

c# - C# Visual Studio 2017 版本 15.1.1 中的 Linq 查询内部的 string Text.ToUpper() 速度较慢

c# - 嵌套循环以获得每个

c# - Dispatcher.BeginInvoke 始终返回 DispatcherOperationStatus.Pending 状态

mvvm - ViewModel 之间的通信

wpf - 使用 CommandParameters 和 MultiBindings?

带有 Click 事件的 WPF 图像控件