0

I'd like to bind two class properties to a combobox's display. Meaning:

Jack - SupplyChain 
Sarah - HR 
James - IT 

I have the following class:

public class MyUser {
  public string Name {get;set;}
  public int EmpID {get;set;}
  public string Department {get;set;}
}

When I set the combobox to just a single property, DisplayMemberPath="Name", I see the object name instead in the drop down.

I'm not sure how to make it bind to two properties, much less one. Does anyone know how to do that?

I am adding MyClass objects to the combobox:

MyComboBox.Items.Add(classInstance);

since I want to pull out the full class that was selected. This will happen on a button click event.

1 Answer 1

1

Don't manipulate UI elements in procedural code in WPF. That's what XAML is for.

Create a simple ViewModel:

public class MyViewModel
{
    public ObservableCollection<MyUser> Users {get;set;}

    public MyUser SelectedUser {get;set;}
}

then set this ViewModel as the UI's DataContext

public MyWindow()
{
    InitializeComponent();
    DataContext = new MyViewModel();
}

And in XAML:

<ComboBox ItemsSource="{Binding Users}"
          SelectedItem="{Binding SelectedUser}">
    <ComboBox.ItemTemplate>
       <DataTemplate>
           <TextBlock>
               <TextBlock.Text>
                   <MultiBinding StringFormat="{}{0} {1}">
                      <Binding Path="Name"/>
                      <Binding Path="Department"/>
                   </MultiBinding>
               </TextBlock.Text>
          </TextBlock>
       </DataTemplate>
    <ComboBox.ItemTemplate>
</ComboBox>

Then you simply populate the Users collection with relevant data, and whenever you need to retrieve the selected value you retrieve the value from the SelectedUser property. No need to manually "read" data from the UI. That's what DataBinding is for.

Sign up to request clarification or add additional context in comments.

3 Comments

What is Users and SelectedUser?
I have multiple components on this UI. Will setting the entire UI to the DataContext of only one component interfere with the other components? Seems like it would be best to just set the DataContext for the component that needs that specific DataContext.
@4thSpace the ViewModel should then contain all the relevant data / presentation logic for the entire View. When I speak of View in terms of MVVM, in WPF that translates conceptually to a Window or UserControl, depending on how your UI is structured.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.