Reputation: 256
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?
Upvotes: 0
Views: 2721
Reputation: 2698
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...
}
}
}
Upvotes: 1
Reputation: 4573
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.
Upvotes: 1