Vishnu Pedireddi
Vishnu Pedireddi

Reputation: 2192

Default Value of ComboBox based on a property

I have a databound ComboBox as follows:

     <ComboBox x:Name="MyEmployee" DisplayMemberPath="Name" ItemsSource={Binding Path=MyEmployeeList}"/>

The DataContext looks like this:

MyDataContext = new DataContext
{
  MyEmployeeList = {
  new Employee{ Name = "Vishnu", Id = 1 },
  new Employee{ Name = "Satyam", Id = 2 },
  },

  PermanentEmployee = "Vishnu";
};

I would like to be able to set a default value of the ComboBox based on the value of another property: "PermanentEmployee".

It can safely be assumed that "PermanentEmployee" will be among one of the "Name" property in the "EmployeeList".

How do I set such a default value for the ComboBox ?

Upvotes: 0

Views: 337

Answers (2)

rfresia
rfresia

Reputation: 556

You would use the SelectedValue property, example:

<ComboBox x:Name="MyEmployee" DisplayMemberPath="Name" ItemsSource="{Binding Path=MyEmployeeList}" Height="25" Width="50" SelectedValue="{Binding Path=PermanentEmployee}"/>

Modified:

Correct missed that, in the view model make the PermanentEmployee a Employee data type. Example:

   public Employee PermanentEmployee
    {
        get;
        set;
    }

Then in your constructor do the following:

PermanentEmployee = MyEmployeeList.Where(r => r.Name == "Vishnu").Single();

Upvotes: 0

Rachel
Rachel

Reputation: 132658

You can use either SelectedItem, or SelectedValue and SelectedValuePath

Since WPF compares objects by reference, SelectedValue will only work if the .Equals() of item is true, so if you're comparing objects then you have to have your SelectedItem point to the exact same reference in memory as the item in the ItemsSource. For example,

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");

Based on the code you showed in your question, you're best off with SelectedValue and SelectedValuePath

<ComboBox x:Name="MyEmployee" 
          DisplayMemberPath="Name" 
          ItemsSource="{Binding Path=MyEmployeeList}"
          SelectedValue="{Binding PermanentEmployee}"
          SelectedValuePath="Name" />

Upvotes: 2

Related Questions