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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With