我有一个具有ID(INT32(和名称(字符串(的类人。人物集合的名称以Combobox(DisplayMemberPath =" name"(显示。我想将所选项目的ID绑定到ViewModel中的属性INT32属性。
我尝试了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}"
/>
尝试这个。
SelectedValue="{Binding SelectedId, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
SelectedValuePath="Id"
更新:
我准备了一个工作正常的样品。我希望它能澄清您。(实施自己由您自己制作的InotifyPropertychang(
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"/>
如果它主要是获取所选项目而不是绑定。
您可以在不将其绑定到额外属性的情况下获取所选项目。当选择另一个项目时,您可以使用ICollectionView
在ViewModel中获取事件。
ViewModel的代码
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"/>