0

I have a ListBox that is bound to an ObservableCollection of Customers. The XAML code for this is:

<ListBox x:Name="lb_Customers" Height="683" ItemsSource="{Binding Path=Customers, UpdateSourceTrigger=PropertyChanged}">
     <ListBox.ItemTemplate>
          <DataTemplate>
               <Label Margin="0,0,0,0" Padding="0,0,0,0" Content="{Binding Name}" />
          </DataTemplate>
      </ListBox.ItemTemplate>
</ListBox>

This points over to some code in my MainViewModel class:

public ObservableCollection<Customer> Customers
{
    get { return _customers; }
    set
    {
        Set("Customers", ref _customers, value);
        this.RaisePropertyChanged("Customers");
    }
}

When I select a customer in this listbox, I'd like to execute some code that goes and compiles the customer's order history.

However, I have no idea how to do this using DataBinding/CommandBinding.

My question: where do I even begin?

Emily
  • 256
  • 2
  • 14

2 Answers2

1

You can add a "currentlyselected" object to your viewmodel and bind it against "SelectedItem" property of the listbox. Then do your desired actions in the "set" accessor.

Tormod
  • 4,551
  • 2
  • 28
  • 50
1

As Tormond suggested:

Change

<ListBox x:Name="lb_Customers" Height="683" ItemsSource="{Binding Path=Customers, UpdateSourceTrigger=PropertyChanged}">

to

<ListBox x:Name="lb_Customers" Height="683" ItemsSource="{Binding Path=Customers, UpdateSourceTrigger=PropertyChanged}", SelectedValue="{Binding SelectedCustomer}">

Then in your ViewModel add:

private Customer _selectedCustomer;
public Customer SelectedCustomer
{
    get {}
    set
    {
        if (_selectedCustomer != value)
        {
            Set("SelectedCustomer", ref _selectedCustomer, value);
            this.RaisePropertyChanged("SelectedCustomer");

            // Execute other changes to the VM based on this selection...
        }
    }
}
EtherDragon
  • 2,679
  • 1
  • 18
  • 24
  • How does `SelectedValue` differ from `SelectedItem`? Attempting to bind `SelectedItem` didn't work, but I'll try it with this. Mostly I'm curious why one works over the other. – Emily Feb 08 '13 at 14:52
  • http://stackoverflow.com/questions/4902039/difference-between-selecteditem-selectedvalue-and-selectedvaluepath This SO thread describes quite nicely the difference between SelectedValue and SelectedItem – EtherDragon Feb 08 '13 at 21:04