组合框绑定到选定值事件

本文关键字:事件 绑定 组合 | 更新日期: 2023-09-27 18:18:01

我想在用户在组合框中选择不同的值时执行一些函数。

我使用MVVM模式。

你知道在这种情况下我是如何进行数据绑定的吗?

组合框绑定到选定值事件

绑定到SelectedItem的属性。在属性的setter中,执行你的函数。设置SelectedItem = "{绑定路径= SomeProperty} "

您可能需要绑定到SelectedValue, SelectedItemSelectedIndex,这取决于您想要做什么:

public class MyViewModel : INotifyPropertyChanged
{
    public ObservableCollection<MyObj> MyCollection { get; private set; }
    private MyObj _theItem;
    public MyObj TheItem
    {
        get { return _theItem; }
        set
        {
            if (Equals(value, _theItem)) return;
            _theItem= value;
            //Or however else you implement this...
            OnPropertyChanged("TheItem");
            //Do something here.... OR
            //This will trigger a PropertyChangedEvent if you're subscribed internally.
        }
    }
    private string _theValue;
    public string TheValue
    {
        get { return _theValue; }
        set
        {
            if (Equals(value, _theValue)) return;
            _theValue= value;
            OnPropertyChanged("TheValue");
        }
    }
    private int _theIndex;
    public int TheIndex
    {
        get { return _theIndex; }
        set
        {
            if (Equals(value, _theIndex)) return;
            _theIndex = value;
            OnPropertyChanged("TheIndex");
        }
    }
}
public class MyObj
{
    public string PropA { get; set; }
}
 <!-- Realistically, you'd only want to bind to one of those -->
 <!-- Most likely the SelectedItem for the best usage -->
 <ItemsControl ItemsSource="{Binding Path=MyCollection}"
               SelectedItem="{Binding Path=TheItem}"
               SelectedValue="{Binding Path=TheValue}"
               SelectedIndex="{Binding Path=TheIndex}"
               />