2010-09-04 25 views
0

在MVVM模型事件我有事件定義的COMBOX控制在我的MainPage.xaml中如何定義在Silverlight

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

private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) 
     { 

     } 

現在怎麼辦,我們定義爲在MVVM模型COMBOX控制的事件。

以及我們如何將集合列表綁定到組合框。我使用SL 3

感謝

王子

回答

1

在XAML中,可以綁定的ItemSource和的SelectedItem,如下圖所示:

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> 

在MainPage.xaml.cs中,您的選擇更改方法可能只需撥打視圖模型的方法,因爲你正在使用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(); 
    } 
} 

您的視圖模型將有MyItems收集和的SelectedItem綁定到:

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; 
} 

根據您使用的SelectionChanged方法,您可能不再需要它,因爲這會將SelectedItem綁定到Vi ewModel。

希望這會有所幫助!

相關問題