0

我有一个数据绑定的组合框,如下所示:

     <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 设置这样的默认值?

4

2 回答 2

2

您可以使用SelectedItem, 或SelectedValueSelectedValuePath

由于 WPF 通过引用比较对象,SelectedValue因此仅在.Equals()of 项为真时才有效,因此如果您正在比较对象,那么您必须将您的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");

根据您在问题中显示的代码,您最好使用SelectedValueSelectedValuePath

<ComboBox x:Name="MyEmployee" 
          DisplayMemberPath="Name" 
          ItemsSource="{Binding Path=MyEmployeeList}"
          SelectedValue="{Binding PermanentEmployee}"
          SelectedValuePath="Name" />
于 2012-08-27T19:51:50.077 回答
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 => r.Name == "Vishnu").Single();

于 2012-08-27T18:56:11.987 回答