只是一起进行了一个测试,这两个都对我有用:
使用完整的语法:
<TextBox Name="Threshold"
Margin="5"
Grid.Column="1">
<i:Interaction.Triggers>
<i:EventTrigger EventName="KeyDown">
<cal:ActionMessage MethodName="ExecuteFilterView">
<cal:Parameter Value="$executionContext"/>
</cal:ActionMessage>
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
使用 CM 语法(更喜欢这个,因为它更具可读性)
<TextBox Name="Threshold"
Margin="5"
Grid.Column="1"
cal:Message.Attach="[Event KeyDown] = [Action ExecuteFilterView($executionContext)]" />
这是测试虚拟机:
public class MainWindowViewModel
{
public void ExecuteFilterView(ActionExecutionContext context)
{
// This method is hit and the context is present and correct
}
}
你能发布你的完整代码 - 你确定你的框架设置正确吗?(您是否遵循了入门示例?
http://caliburnmicro.codeplex.com/wikipage?title=Basic%20Configuration%2c%20Actions%20and%20Conventions&referringTitle=Documentation
编辑:
好的,在你澄清之后,我可以给你一些例子来说明如何做到这一点 - 我会告诉你我的个人喜好和原因,但选择最适合你的那个
- 使用
ActionExecutionContext
和转换 eventargs:
cal:Message.Attach="[Event KeyDown] = [Action ExecuteFilterView($executionContext)]"
public void ExecuteFilterView(ActionExecutionContext context)
{
var keyArgs = context.EventArgs as KeyEventArgs;
if (keyArgs != null && keyArgs.Key == Key.Enter)
{
// Do Stuff
}
}
EventArgs
直接使用
cal:Message.Attach="[Event KeyDown] = [Action ExecuteFilterView($eventArgs)]"
public void ExecuteFilterView(KeyEventArgs keyArgs)
{
if (keyArgs.Key == Key.Enter)
{
// Do Stuff
}
}
- 我个人的最爱,创建自己的
SpecialValues
字典条目:
在你的Bootstrapper.Configure
方法...
MessageBinder.SpecialValues.Add("$pressedkey", (context) =>
{
// NOTE: IMPORTANT - you MUST add the dictionary key as lowercase as CM
// does a ToLower on the param string you add in the action message, in fact ideally
// all your param messages should be lowercase just in case. I don't really like this
// behaviour but that's how it is!
var keyArgs = context.EventArgs as KeyEventArgs;
if (keyArgs != null)
return keyArgs.Key;
return null;
});
你的行动:
cal:Message.Attach="[Event KeyDown] = [Action ExecuteFilterView($pressedKey)]"
和代码:
public void ExecuteFilterView(Key key)
{
if (key == Key.Enter)
{
// Do Stuff
}
}
这是我最喜欢的原因?这意味着您的虚拟机只接收您想要的值(大多数时候您不关心很多其他参数)并且您不需要知道如何或费心地转换 eventargs - 您只需操作关于价值。显然使用最适合你的东西
还值得注意的是,如果您有其他类型的子类控件,KeyEventArgs
这将适用于它们。如果他们没有子类KeyEventArgs
化但他们仍然返回一个类型的值,Key
这仍然可以工作,因为如果第一个失败,您可以向委托添加另一个转换:
例如
MessageBinder.SpecialValues.Add("$pressedkey", (context) =>
{
var keyArgs = context.EventArgs as KeyEventArgs;
if (keyArgs != null)
return keyArgs.Key;
// Ok so it wasn't KeyEventArgs... check for some other type - maybe a 3rd party implementation
var thirdPartyKeyArgs = context.EventArgs as ThirdPartyKeyArgs;
if (thirdPartyKeyArgs != null)
return thirdPartyKeyArgs.KeyProperty;
return null;
});