我正在使用 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 中定义的目标函数吗?可能是范围相关的问题吗?
在此先感谢,干杯,吉安卢卡。