wpf EventTrigger 不会为 UserControl 的 Loaded 事件触发
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15486594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
EventTrigger not firing for Loaded event of UserControl
提问by blue18hutthutt
I have a UserControl with the following event trigger:
我有一个带有以下事件触发器的 UserControl:
<UserControl x:Class="TestApp.Views.MyUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
>
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<i:InvokeCommandAction Command="{Binding OnLoadedCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
It is being set via the constructor of the UserControl (please ignore the ServiceLocator ..this is just a quick prototype):
它是通过 UserControl 的构造函数设置的(请忽略 ServiceLocator ..这只是一个快速原型):
public MyUserControl()
{
InitializeComponent();
DataContext = ServiceLocator.Current.GetInstance<DirectorySearchViewModel>();
}
In my view-model I have the following:
在我的视图模型中,我有以下内容:
public ICommand OnLoadedCommand { get; private set; }
public MyUserControl()
{
OnLoadedCommand = new DelegateCommand(OnLoaded);
}
public void OnLoaded()
{
}
OnLoaded never gets called. If I change the EventName to say ..MouseDown, then it works but it just won't work for Loaded
OnLoaded 永远不会被调用。如果我将 EventName 更改为 ..MouseDown,则它可以工作,但它不适用于 Loaded
Pretty sure it's a stupid mistake (swear I've done this a million times before in the past) but can't seem to figure it out right now
很确定这是一个愚蠢的错误(发誓我过去做过一百万次)但现在似乎无法弄清楚
采纳答案by blue18hutthutt
public MyUserControl()
{
DataContext = ServiceLocator.Current.GetInstance<DirectorySearchViewModel>();
InitializeComponent();
}
The Aristocrats.
贵族们。
回答by Mark Feldman
For anyone else that stumbles across this you can do it without code behind like this:
对于偶然发现此问题的其他任何人,您都可以在没有代码的情况下这样做:
<UserControl x:Class="TestApp.Views.MyUserControl"
... etc...
x:Name="theControl"
>
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<i:InvokeCommandAction
Command="{Binding ElementName=theControl, Path=OnLoadedCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>

