簡體   English   中英

WPF,MVVM和嵌套UserControls的事件處理

[英]WPF, MVVM, and event handling for nested UserControls

我有一個WPF應用程序,我正在嘗試實現MVVM。 主窗口有一個viewmodel和一個自定義用戶控件。 此用戶控件包含一個文本框和一個按鈕,並從主父窗口共享datacontext。 一切都很好...

我已經能夠將文本框綁定到viewmodel中的變量,並且它可以成功運行。 但是......對於我的生活,我無法將事件處理程序從按鈕綁定到viewmodel。 我一直收到以下錯誤:

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

我知道這是MVVM新手的常見問題。 我在網上搜索過,似乎沒什么用。 誰能解釋我做錯了什么?

以下是一些示例代碼:主窗口:

<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 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>

您應該在按鈕上使用Command ,並在ViewModel中使用ICommand屬性。

Click屬性需要代碼隱藏文件中的一個方法,該方法不能“綁定”OnClick。 因此,要么使用Command,要么只在.xaml.cs文件中鍵入應該在單擊按鈕時調用的方法名稱。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM