我有一个数据绑定ComboBox如下:
<ComboBox x:Name="MyEmployee" DisplayMemberPath="Name" ItemsSource={Binding Path=MyEmployeeList}"/>
DataContext看起来像这样:
MyDataContext = new DataContext
{
MyEmployeeList = {
new Employee{ Name = "Vishnu", Id = 1 },
new Employee{ Name = "Satyam", Id = 2 },
},
PermanentEmployee = "Vishnu";
};
我希望能够根据另一个属性的值设置ComboBox的默认值:“PermanentEmployee”。
可以安全地假设“PermanentEmployee”将成为“EmployeeList”中“Name”属性之一。
如何为ComboBox设置这样的默认值?
答案 0 :(得分:2)
您可以使用SelectedItem
,SelectedValue
和SelectedValuePath
由于WPF通过引用比较对象,SelectedValue
仅在项的.Equals()
为真时才有效,因此如果您要比较对象,则必须指向SelectedItem
点内存中的引用与ItemsSource
中的项完全相同。例如,
MyEmployeeList = {
new Employee{ Name = "Vishnu", Id = 1 },
new Employee{ Name = "Satyam", Id = 2 },
};
// Won't work
PermanentEmployee = new Employee{ Name = "Vishnu", Id = 1 };
// Works
PermanentEmployee = MyEmployeeList.FirstOrDefault(p => p.Name == "Vishnu");
根据您在问题中显示的代码,您最好使用SelectedValue
和SelectedValuePath
<ComboBox x:Name="MyEmployee"
DisplayMemberPath="Name"
ItemsSource="{Binding Path=MyEmployeeList}"
SelectedValue="{Binding PermanentEmployee}"
SelectedValuePath="Name" />
答案 1 :(得分:0)
您将使用SelectedValue属性,例如:
<ComboBox x:Name="MyEmployee" DisplayMemberPath="Name" ItemsSource="{Binding Path=MyEmployeeList}" Height="25" Width="50" SelectedValue="{Binding Path=PermanentEmployee}"/>
修改:
正确错过了,在视图模型中使PermanentEmployee成为Employee数据类型。例如:
public Employee PermanentEmployee
{
get;
set;
}
然后在构造函数中执行以下操作:
PermanentEmployee = MyEmployeeList.Where(r =&gt; r.Name ==“Vishnu”)。Single();