Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF, MVVM, and event handling for nested UserControls

Tags:

c#

.net

mvvm

wpf

xaml

I have a WPF application and I'm trying to implement MVVM. The main window has a viewmodel and a custom user control. This user control contains a textbox and a button and shares the datacontext from the main parent window. All is good...

I have been able to bind the textbox to a variable within the viewmodel, and it works successfully. But... for the life of me I'm unable to bind an event handler from the button to the viewmodel. I keep recieving the following error:

Unable to cast object of type 'System.Reflection.RuntimeEventInfo' to type 'System.Reflection.MethodInfo'.

I know this is a common problem with those new to MVVM. I have scoured the web and nothing seems to work. Can anyone explain what the heck I am doing wrong?

Here is some sample code: Main Window:

<Window x:Class="Mvvm.View.MainWindowView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:view="clr-namespace:ZeeZor.Kiosk.Mvvm.View"
        WindowStyle="None"
        WindowState="Maximized" >
    <Grid >
        <view:ControlPanelView
            Margin="5, 0, 5, 0"
            HorizontalAlignment="Stretch"
            VerticalAlignment="Stretch" >
        </view:ControlPanelView>            
    </Grid>
</Window>

UserControl:

<UserControl x:Class="Mvvm.View.ControlPanelView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <TextBlock Grid.Row="0" TextAlignment="Right" Text="{Binding Total}" Margin="0,5,20,5" />
        <Button Grid.Row="1" Content="Test" Click="{Binding Path=OnClick}" Width="220" Height="100"/>
    </Grid>
</UserControl>
like image 761
mrtedweb Avatar asked Apr 26 '13 20:04

mrtedweb


1 Answers

You should use Command on the button instead, and have an ICommand property in your ViewModel.

The Click property expects a method in the code-behind file, which can't be "bound to" OnClick. So either use Command, or only type the method name from the .xaml.cs file that should be invoked when the button is clicked.

like image 89
Patrick Avatar answered Oct 07 '22 01:10

Patrick