lte__ lte__ - 1 year ago 83
C# Question

Function binding normative

I'm new to WPF and MVVM and am going through an example on Microsoft's site, however, I don't see how the binding is done. In the example linked, there's this piece of code:

public partial class MainPage : UserControl
private PartInventoryViewModel viewModel;

public MainPage()
viewModel = new PartInventoryViewModel();
this.DataContext = viewModel;

private void PartSearchButton_Click(object sender, RoutedEventArgs e)


It notifies the ViewModel instance when the user clicks the PartSearchButton.

But how? There's no binding in the XAML above for the
in the example. Is it a normative that if you name your function YourButtonName_Clicked() it will trigger when the button is clicked? Or does it become a listener if you create the function with the
(object sender, RoutedEventArgs e)
arguments? Or is there some XAML which this tutorial is not showing, where the binding occurs?

Thank you for your answer, sorry if it's a newb one.

Answer Source

Microsoft is not showing all the code that is necessary here. Basically all that this code does is setting the DataContext to a newly instantiated ViewModel. The PartSearchButton_Click is a simple Click-Event-Handler that should look something like this in your XAML-file:

<Button Click="PartSearchButton_Click">Search</Button>

The whole binding thing is happening in these 2 lines of the datagrid in your xaml file:

ItemsSource="{Binding Parts}" 
SelectedItem="{Binding CurrentPart, Mode=TwoWay}"

This is telling the DataGrid that it should look for a public property called Parts in the current DataContext. You set the DataContext to a new instance of PartInventoryViewModel, so there needs to be a public property Parts somewhere in there. I guess the PartInventoryViewModel class will be explained a bit further down on the Microsofts site.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download