views:

53

answers:

3

Hello,

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 shall I bind the command using MVVM? Thanks.

A: 

I set the DataContext of page as model.

Archie
+1  A: 

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>
Ray Booysen
A: 

If you want to see an example of using MVVM and commands in Silverlight without having to use a click event handler check out my blog post How to Implement MVVM, INotifyChanged and ICommand in a Silverlight Application

Jag Reehal