Binding command to button in silverlight 4 using mvvm
I have a user control called HomePage.xaml
. I'm creating a model instance (using MVVM pattern) in the code behind file in the constructor of page as
MainViewModel model = new MainViewModel();
I have a button in HomePage.xaml
which I want to bind to the command inside MainViewModel
called GetData()
and want to populate the data in datagrid. MainViewModel
has an ObservableCollection
which I would use to bind the data in datagrid.
Populating the data in datagrid without binding command works fine.
I'm binding the button as:
<StackPanel x:Name="stkPanelInput" Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center">
<Button x:Name="buttonGetData" Width="70" Content="GetData" Command="{Binding GetData}" Click="buttonGetData_Click"/>
</StackPanel>
How shal开发者_如何学Gol I bind the command using MVVM?
Like Archie said, set the DataContext of your page to the instance of your MainViewModel.
DataContext = model;
Then you have your XAML look like this:
<StackPanel x:Name="stkPanelInput" Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center">
<Button x:Name="buttonGetData" Width="70" Content="GetData" Command="{Binding GetDataCommand}" Click="buttonGetData_Click"/>
</StackPanel>
精彩评论