对于初始 GotFocus 事件,EventToCommand 失败

发布于 2024-12-14 10:16:45 字数 1128 浏览 2 评论 0原文

我开始在当前的项目中应用Mvvm设计模式,使用的框架是Mvvm Light工具包。现在,我在使用 EventToCommand 处理“GotFocus”事件时遇到了问题。 xaml 文件类似于:

<TextBox x:Name="TextBox1">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="GotFocus">
            <cmd:EventToCommand Command="{Binding TestCommand}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
 </TextBox>

每当“GotFocus”被触发时,我想在视图模型中执行 TestCommand。 但问题是,“TestCommand”不会在初始“GotFocus”(即加载窗口时)执行。我进行了调试,发现“GotFocus”事件实际上已被触发,但由于未知原因未调用触发器。 然后我将焦点设置在“Window.Loaded”事件处理程序中,它仍然失败。

protected void WindowLoaded(object sender, RoutedEventArgs e)
    {
        FocusManager.SetFocusedElement(this, TextBox1); // The focus is moved to TextBox1 but the associated command is not executed.
    }

但是如果我将焦点设置在“Window.Activated”事件处理程序中,那就没问题了。

    protected void WindowActivated(object sender, EventArgs e)
    {
        FocusManager.SetFocusedElement(this, TextBox1); // The focus is moved to TextBox1 and the command is executed.
    }

我对发生的事情感到非常困惑。有人能详细解释一下吗?

I begin to apply the Mvvm design pattern in my current project and the framework I used is Mvvm Light toolkit. Now I encoutered a problem when using the EventToCommand to handle "GotFocus" event.
The xaml file is something like:

<TextBox x:Name="TextBox1">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="GotFocus">
            <cmd:EventToCommand Command="{Binding TestCommand}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
 </TextBox>

I want to execute the TestCommand in the view model whenever the "GotFocus" is fired.
But the problem is that the "TestCommand" is not executed for the initial "GotFocus"(ie. when the window is loaded). I have debugged and found that the "GotFocus" event was actually fired but the Trigger was not invoked for unknown reason.
Then I set the focus in the "Window.Loaded" event handler, it still failed.

protected void WindowLoaded(object sender, RoutedEventArgs e)
    {
        FocusManager.SetFocusedElement(this, TextBox1); // The focus is moved to TextBox1 but the associated command is not executed.
    }

But If I set the focus in the "Window.Activated" event handler, it is OK.

    protected void WindowActivated(object sender, EventArgs e)
    {
        FocusManager.SetFocusedElement(this, TextBox1); // The focus is moved to TextBox1 and the command is executed.
    }

I am very confused about what happened. Could anyone explain it in detail?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文