当前,当我将两个组合框绑定到同一项目源时 然后将组合框的SelectedItem设置为两个单独的属性 然后将组合框的SelectedIndex设置为两个不同的索引
用户界面加载后 组合框加载并显示正确的索引 但是,在我从第二个组合框中手动选择其他项目之前,在viewModel中设置了Person的属性,但没有设置PersonTwo的属性。
如果我随后创建了一个单独但相同的列表,并将第二个组合框的itemsource绑定到该列表,则PersonTwo的数据将设置为selectedIndex
我试图进行搜索以更好地了解正在发生的事情,但是我离寻找答案还很近。我不明白为什么两个组合框都使用相同的商品来源时会出现这种情况。
最小的工作示例: 型号
namespace WpfApp1
{
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
}
ViewModel
using System.Collections.Generic;
namespace WpfApp1
{
public class GenericViewModel
{
public GenericViewModel()
{
People = new List<Person>();
Person personToMakeList = null;
People.Add(personToMakeList = new Person(){Age = 10,Id=1,Name="John"});
People.Add(personToMakeList = new Person() { Age = 20, Id = 2, Name = "Amber" });
People.Add(personToMakeList = new Person() { Age = 30, Id = 3, Name = "Amy" });
People.Add(personToMakeList = new Person() { Age = 40, Id = 4, Name = "Joey" });
Person = new Person();
PersonTwo = new Person();
}
public Person Person { get; set; }
public List<Person> People { get; set; }
public Person PersonTwo { get; set; }
}
}
查看
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid.DataContext>
<local:GenericViewModel/>
</Grid.DataContext>
<StackPanel Orientation="Vertical">
<StackPanel>
<ComboBox ItemsSource="{Binding People}"
SelectedIndex="0"
SelectedItem="{Binding Person}"
DisplayMemberPath="Name"/>
</StackPanel>
<StackPanel Orientation="Vertical">
<TextBlock Text="Person One"></TextBlock>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Age: "/>
<TextBlock Text="{Binding Person.Age}"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Id: "/>
<TextBlock Text="{Binding Person.Id}"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Name: "/>
<TextBlock Text="{Binding Person.Name}"/>
</StackPanel>
</StackPanel>
<StackPanel>
<ComboBox ItemsSource="{Binding People}"
SelectedIndex="3"
SelectedItem="{Binding PersonTwo}"
DisplayMemberPath="Name"/>
</StackPanel>
<StackPanel Orientation="Vertical">
<TextBlock Text="Person Two"></TextBlock>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Age: "/>
<TextBlock Text="{Binding PersonTwo.Age}"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Id: "/>
<TextBlock Text="{Binding PersonTwo.Id}"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Name: "/>
<TextBlock Text="{Binding PersonTwo.Name}"/>
</StackPanel>
</StackPanel>
</StackPanel>
</Grid>