views:

33

answers:

1

hi,

i have an combox control defined with events in my mainpage.xaml

  <Grid x:Name="LayoutRoot">
<ComboBox SelectionChanged="ComboBox_SelectionChanged"></ComboBox>
  </Grid>

private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

now how do we defined events for combox control in mvvm model .

and how do we bind the collection list to combo box. i am using SL 3

thanks

prince

A: 

In your xaml, you can bind the ItemSource and SelectedItem as shown below:

MainPage.xaml

<UserControl x:Class="App1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:App1"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">

<UserControl.DataContext>
    <local:MainPage_ViewModel/>
</UserControl.DataContext>

<Grid x:Name="LayoutRoot" Background="White">
    <ComboBox ItemsSource="{Binding MyItems}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}" SelectionChanged="ComboBox_SelectionChanged" Height="30" Width="100"/>
</Grid>

In the MainPage.xaml.cs, your Selection changed method could just call the method on your ViewModel since you are using SL3:

MainPage.xaml.cs

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

    private MainPage_ViewModel viewModel
    {
        get { return this.DataContext as MainPage_ViewModel; }
    }

    private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        this.viewModel.SelectionChanged();
    }
}

Your ViewModel would have the MyItems collection and the SelectedItem to bind to:

MainPage_ViewModel.cs

public class MainPage_ViewModel : INotifyPropertyChanged
{
    public ObservableCollection<string> MyItems
    {
        get { return myItems; }
        set { myItems = value; }
    }
    private ObservableCollection<string> myItems = new ObservableCollection<string>() { "One", "Two", "Three" };

    public string SelectedItem
    {
        get { return selectedItem; }
        set { selectedItem = value; }
    }
    private string selectedItem = string.Empty;

    public void SelectionChanged()
    {
        //Perform logic that needs to happen when selection changes
    }

    public void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
}

Depending on what you were using your SelectionChanged method for, you may no longer need it since this would bind the SelectedItem to the ViewModel.

Hope this helps!

JSprang

related questions