Combobox selectedValue绑定了一个类的属性而不是更新

时间:2017-10-31 10:28:10

标签: c# wpf combobox

public class Rma
{
    public int Id { get; set; } 
}

和这个属性:

 public static readonly DependencyProperty ActRmaProperty =
    DependencyProperty.Register("ActRma", typeof(Rma), typeof(MainWindow),new PropertyMetadata(null));
    public Rma ActRma
    {
        get { return (Rma)GetValue(ActRmaProperty); }
        set { SetValue(ActRmaProperty, value); OnPropertyChanged("ActRma"); }
    }
public static readonly DependencyProperty ItemsByIdProperty =
        DependencyProperty.Register("ItemsById", typeof(ObservableCollection<int>), typeof(MainWindow), new PropertyMetadata(null));
public ObservableCollection<int> ItemsById
    {
        get { return (ObservableCollection<int>)GetValue(ItemsByIdProperty); }
        set { SetValue(ItemsByIdProperty, value); OnPropertyChanged("ItemsById"); }
    }

和xaml中的组合框:

 <ComboBox ItemsSource="{Binding ItemsById}" DisplayMemberPath="Id"
     SelectedValuePath="Id" SelectedValue="{Binding ActRma.Id , UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
                                          SelectionChanged="ComboBox_SelectionChanged"
                                          Margin="3"
                                          AlternationCount="1"/>

当我通过ID后面的代码更改时,copmbobox没有显示该值。 e.g:

ItemsById = new ItemById();
ItemsById.Add(1);
ItemsById.Add(2);
ActRma.Id = 2;

2 个答案:

答案 0 :(得分:0)

从我在您的示例中看到的内容中,您使用DependencyProperty来查找Window中的项目。 ComboBox旨在使用集合,因此我们可以在MvvM(Model-View-ViewModel)中使用它。
ViewModel.cs:

private List<int> _cmbList;

public List<int> CmbList//this is the collection that we will use to hold values
{
    get { return _cmbList; }
    set { _cmbList = value; OnPropertyChanged("CmbList"); }
}
//with additional property
private int _ActRma;

public int ActRma
{
    get { return _ActRma; }
    set { _ActRma = value; OnPropertyChanged(nameof(ActRma)); }// In here you can handle the changed value of your ComboBox. No need for event handler in this case as setter is called everytime you change selected item in UI.
}

然后在MainWindow.xaml中引用您的视图模型:

xmlns:vm="clr-namespace:VM;assembly=VM"  

然后应该像这样设置MainWindow.xaml的DataContext

<Window.DataContext>
    <vm:MainViewModel/>
</Window.DataContext>  

此时,您的窗口及其中声明的所有元素将继承DataContext对象,即ViewModel。 然后在我们的ComboBox中使用Collection,您可以像这样使用它:

<ComboBox ItemsSource="{Binding CmbItems}" SelectedItem="{Binding ActRmaId}" AlternationCount="1"/><!-- here we hold the Id of the selected item, we don't need to set the Display path as we are binding to the int and this being primitive type doesn't have any properties! -->

答案 1 :(得分:0)

要扩展XAMlMAX的答案 - 除非您已在代码隐藏中将自己的datacontext设置为自身,否则您需要在xaml本身中执行 - 定义x:name并在其中使用ElementName绑定定义 -

ItemsSource="{Binding ItemsById,ElementName=_this}"...