WPF组合框:将SelectedItem绑定到类成员

时间:2019-05-14 09:14:35

标签: c# wpf xaml combobox binding

我有一个具有ID(Int32)和Name(String)的Person类。 Persons集合的名称显示在ComboBox中(DisplayMemberPath =“ Name”)。我想将所选项目的ID绑定到视图模型中的属性Int32 SelectedId。

我尝试了SelectedValue =“ {Binding Path = SelectedId,Mode = TwoWay}” 和SelectedValuePath =“ {Binding Path = SelectedId,Mode = TwoWay}”都不起作用。

<ComboBox Name="cmbPersons"
    ItemsSource="{Binding Source={StaticResource vm},Path=Persons}"
    DisplayMemberPath="Name"
    SelectedValue="Id"
    SelectedValue="{Binding Path=SelectedId, Mode=TwoWay}"
/>

2 个答案:

答案 0 :(得分:0)

尝试一下。

SelectedValue="{Binding SelectedId, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
SelectedValuePath="Id"

更新

我准备了一个运行良好的样品。我希望它能使您澄清。 (自行实现INotifyPropertyChanged)

MainWindow.xaml.cs:

public partial class MainWindow : Window
{
    public ObservableCollection<Person> Persons { get; set; }
    public int SelectedId { get; set; }
    public MainWindow()
    {
        InitializeComponent();

        DataContext = this;

        Persons = new ObservableCollection<Person>
        {
            new Person { Id = 1, Name = "Raj" },
            new Person { Id = 2, Name = "Ram" }
        };
    }
}

Person.cs:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

MainWindow.xaml:

   <ComboBox Width="100" Height="30" ItemsSource="{Binding Persons}" DisplayMemberPath="Name" SelectedValue="{Binding SelectedId}" SelectedValuePath="Id"/>

答案 1 :(得分:0)

如果主要是要获取所选项目,而不是绑定。

您可以获取所选项目,而无需将其绑定到其他属性。您可以使用ICollectionView在选择另一个项目时在视图模型中获取事件。

视图模型的代码

List<PersonVm> personVms;
private ICollectionView _persons;

public ICollectionView Persons
{
    get => _persons;
    set
    {
        if (Equals(value, _persons)) return;
        _persons = value;
        OnPropertyChanged();
    }
}

// call this method in the constructor of the viewmodel
private void Init(){
    // TODO You have to add items to personVms before creating the collection

    Persons = new CollectionView(personVms);

    // Event when another item gets selected
    Persons.CurrentChanged += PersonsOnCurrentChanged;

    // moves selected index to postion 2
    Persons.MoveCurrentToPosition(2); 
}

private void PersonsOnCurrentChanged(object sender, EventArgs e)
{
    // the currently selected item
    PersonVm personVm = (PersonVm)Persons.CurrentItem;

    // the currently selected index
    int personsCurrentPosition = Persons.CurrentPosition;
}

XAML

<ComboBox 
    ItemsSource="{Binding Persons}" 
    DisplayMemberPath="Name"/>