绑定到WPF Combobox的'SelectedItem'的属性的奇怪行为

时间:2010-07-07 20:56:55

标签: c# wpf mvvm combobox

当将属性绑定到WPF组合框的SelectedItem时,我希望每次组合框的选择发生变化时都会调用属性设置器。我没有看到。

当选择被更改时,Combobox是否应该调用绑定的SelectedItem属性设置器?

添加:我实际上有部分绑定:调用属性getter并在首次加载/选择组合框时调用属性setter一次,并且在以后的选择更改时再也不会调用它。 / p>

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

另外,我指的是视图模型属性,而不是依赖属性。至少我没有把它设置为依赖属性。我是新手(惊喜!),所以关于这个主题的任何更多信息都将非常受欢迎。

xaml代码:

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

ViewModel代码(Binded Attributes):

 public Collection<string> KeywordCollectionTypes
    {
        get
        {
            return _KeywordCollectionTypes;
        }
    }

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

            OnPropertyChanged("KeywordCollectionType");
        }
    }

另外一点信息是组合框在DataGrid.RowDetailsTemplate内,所以这种奇怪的更新行为是否与行内的细节有关?

3 个答案:

答案 0 :(得分:2)

我终于弄明白了我遇到的问题。在组合框的组合框中,我需要输入:“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

答案 1 :(得分:1)

你做错了什么。来自我当前的一个项目:

<ComboBox
   ItemsSource="{Binding Configurations}" 
   SelectedItem="{Binding SelectedConfiguration, Mode=TwoWay}"/>

每次所选项目更改时,都会调用SelectedConfiguration属性设置器。

修改

我假设您的对象不是DependencyObject,并且您绑定的属性不是依赖属性。如果它是依赖属性,那么当DK观察时,绑定将通过调用SetValue更新属性值并绕过CLR属性访问器;如果要将逻辑插入到该控制流中,请在注册依赖项属性时引用回调方法。

答案 2 :(得分:0)

这是将组合框的选定项目绑定到数据模型的方法....

 <ComboBox SelectedItem="{Binding Path=MyValue}"/>

其中MyValue是DataContext / Data Model的属性。

如果你想将一个不同的控件(如TextBlock)绑定到所选的项目,这里有一个小例子......

<ComboBox Name="myComboBox" SelectedIndex="0">
   <ComboBoxItem>1</ComboBoxItem>
   <ComboBoxItem>2</ComboBoxItem>
   <ComboBoxItem>3</ComboBoxItem>
</ComboBox>
<TextBlock Text="{Binding ElementName=myComboBox, Path=SelectedItem.Content}"/>

这里,只要ComboBox选择发生变化,文本块就会更新。