Adam Rackis
Adam Rackis

Reputation: 83356

Silverlight Combobox - items with a command

What would be the best way to get the elements of a combobox to each support a Command and CommandParameter?

I'd like to implement the Theme Chooser shown toward the bottom of this blog post, except with a combo box instead of a context menu. I'd need each element of the combobox to support a Command and CommandParameter, and I'd like it to just be plain text, as the combo below is.

        <ComboBox>
            <ComboBox.Items>
                <TextBlock>A</TextBlock>
                <TextBlock>B</TextBlock>
                <TextBlock>C</TextBlock>
            </ComboBox.Items>
        </ComboBox>

I tried hyperlinks, but the main problem there is that when you click directly onto the link text, the combo box does not close.

Is there an easy way to do this?

EDIT

Ok, well the specific goal that I said I wanted to achieve—having a combo change the SL Toolkit theme—is trivially accomplished. I can simply bind the selected item of the combo to a ViewModel property that then exposes the appropriate themeuri which my SL Toolkit theme can bind to, or, since this is purely a UI activity with no business logic, I can just catch the combobox item changed event, and update my themeUri from there.

I am curious though, is there a good way to bind each combo box item to a command with a command parameter? Using a Hyperlink as each comboboxItem seemed promising, but that prevents the CB from closing after you click on an item when you click the actual hyperlink.

Upvotes: 0

Views: 1332

Answers (1)

bendewey
bendewey

Reputation: 40235

You could Bind the selected item to your ViewModel and then the setter would trigger when the Theme was changed.

Xaml:

<ComboBox SelectedItem="{Binding SelectedTheme, Mode=TwoWay}" ItemsSource="{Binding Themes}" />

CodeBehind:

public partial class MainPage : UserControl
{
    public MainPage()
    {
        InitializeComponent();

        DataContext = new MainPageViewModel();
    }
}

ViewModel:

public class MainPageViewModel : INotifyPropertyChanged
{
    public ObservableCollection<string> Themes { get; set; }

    private string _selectedTheme;
    public string SelectedTheme
    {
        get { return _selectedTheme; }
        set
        {
            _selectedTheme = value;
            // Change the Theme
            RaisePropertyChanged("SelectedTheme");
        }
    }

    public MainPageViewModel()
    {
        Themes = new ObservableCollection<string>();
        Themes.Add("Red");
        Themes.Add("Green");
        Themes.Add("Blue");
    }
}

Upvotes: 3

Related Questions