DoctorAV
DoctorAV

Reputation: 1189

Silverlight 5: Binding command to listboxitem

I am beginner in silverlight and all this mvvm pattern is bit confusing.

In my application I have two listboxs one for country and one for states.

What I want to do is when I select a Country from the listbox1 second listbox will display states from the selected country.

i.e I want to bind command in xaml to listboxitem.

I try to find the solution by Google but either solutions was too complex for me to understand or using different mvvm pattern like prism,light etc.

Upvotes: 1

Views: 548

Answers (1)

Duncan Matheson
Duncan Matheson

Reputation: 1726

There are a few different ways of doing this:

1: (Easiest!) Bind the SelectedItem of the first ListBox to your ViewModel. In the Setter for the ViewModel property, change the list that you're binding to the second listbox. Note that your ViewModel property will need to use INotifyPropertyChanged to notify that the list has changed.

Eg: If your xaml looks like:

<ListBox ItemSource="{Binding ListOne}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}"/>
<ListBox ItemSource="{Binding ListTwo}"/>

Then your ViewModel might be a bit like:

public List<MyItem> ListOne { get; set; }

private MyItem _selectedItem
public MyItem SelectedItem
{
    get { return _selectedItem; }
    set
    {
        _selectedItem = value;
        ListTwo = _selectedItem.SubItems;
    }
}

private List<MyOtherItem> _listTwo
public List<MyOtherItem> ListTwo
{
    get { return _listTwo; }
    set
    {
        _listTwo = value;
        RaisePropertyChanged("ListTwo");
    }
}

2: If the data for the second list is literally a property of the items in the first list, you can use an Binding in xaml to directly join them up.

ItemSource="{Binding Path=SelectedItem.MyItemsProperty, ElementName=MyFirstListBoxName}"

3: You can use an EventTrigger with an EventToCommand to turn the SelectedItemChanged event into a Command execution. You're not literally binding a command to the ListBoxItem, you're binding the command to the change.

I would recommend the first option, it's easiest and gives you good control of what's going on without getting too complicated.

Upvotes: 2

Related Questions