5

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>
1
  • I don't think that the Click attribute should use the word Binding, just something like Click="OnClick" Apr 26, 2013 at 20:55

1 Answer 1

6

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.

1
  • Pretty weird: the Click event can be bound to a view model's method in a UWP app!
    – benichka
    Sep 6, 2017 at 11:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.