0

我正在使用 MVVM Light 框架来构建 SL4 应用程序。我的简单应用程序主要由一个主视图(shellView)组成,它分为多个用户控件。它们只是 UI 的方便分离,因此它们没有自己的 ViewModel。

ShellView 包含一个 Keypad(自定义用户控件),其中包含多个 KeypadButtons(自定义用户控件)。

我很确定(因为我已经检查过)DataContext 设置正确,并且它被层次结构中的所有用户控件使用。(ShellView的Datacontext是ShellViewModel,Keypad的DataContext是ShellViewModel等)。

在 ShellViewModel 中,我有一个名为“ProcessKey”的 ICommand (RelayCommand)。

在键盘控件中,我有类似的东西:

<controls:KeypadButton x:Name="testBtn" Text="Hello">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="Click">
                <GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding PressStandardKeyCommand}" />
            </i:EventTrigger>
        </i:Interaction.Triggers>
</controls:KeypadButton>

KeypadButton 基本上是一个包含按钮的网格。捕获 MouseLeftButtonUp 事件并触发自定义“单击”事件。让我向您展示一些代码来轻松解释我在做什么:

public partial class KeypadButton : UserControl
{
    public delegate void KeypadButtonClickHandler(object sender, RoutedEventArgs e);
    public event KeypadButtonClickHandler Click;

public KeypadButton()
{
        // Required to initialize variables
    InitializeComponent();
}

    private void innerButton_Click(object sender, MouseButtonEventArgs e)
    {
        if (Click != null)
            Click(sender, new KeypadButtonEventArgs());
    }
}

public class KeypadButtonEventArgs : RoutedEventArgs
{
    public string test { get; set; }
}

现在,如果我为 innerButton_Click 的主体设置断点,我可以看到 Click 被正确捕获,并且它包含指向 RelayCommand 的点。但是,什么也没有发生:“单击(发件人,新的 KeypadButtonEventArgs());” 被执行,但仅此而已。

为什么会这样?不应该执行 RelayCommand 中定义的目标函数吗?可能是范围相关的问题吗?

在此先感谢,干杯,吉安卢卡。

4

2 回答 2

1

正如其他评论所指出的,这可能与Click事件不是RoutedEvent.

作为一种快速破解,您可能可以使用MouseLeftButtonDown而不是.ClickUserControl

<!-- Kinda Hacky Click Interception -->
<controls:KeypadButton x:Name="testBtn" Text="Hello">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="MouseLeftButtonDown">
                <GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding PressStandardKeyCommand}" />
            </i:EventTrigger>
        </i:Interaction.Triggers>
</controls:KeypadButton>

您可以考虑的另一个选择是继承 fromButton而不是UserControl. Silverlight Show 有一篇关于从可能与此相关的 TextBox 继承的文章。

于 2011-03-10T18:59:25.447 回答
0

路由事件应该这样定义(参见文档):

public static readonly RoutedEvent TapEvent = EventManager.RegisterRoutedEvent(
    "Tap", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyButtonSimple));

// Provide CLR accessors for the event
public event RoutedEventHandler Tap
{
        add { AddHandler(TapEvent, value); } 
        remove { RemoveHandler(TapEvent, value); }
}
于 2011-03-10T10:00:34.707 回答