WPF 图像的焦点/失去焦点事件未触发



你能帮我,为什么GotFocus和LostFocusa事件不触发当我点击图像,然后到文本框?

我的XAML

:

<Window x:Class="imageclick.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <StackPanel>
            <Image Source="Untitled.png" GotFocus="GF" LostFocus="LF" Focusable="True"></Image>
            <TextBox ></TextBox>
        </StackPanel>
    </Grid>
</Window>

我不明白为什么GotFocus/LostFocus事件从未触发

Thanks in advance

更新:当我设置tabindex时,当tab到达图像事件触发时,但我无法用鼠标点击

形象不是一个 Control 。只有控件才能获得焦点。使用MouseEnterMouseLeave事件代替GotFocus和LostFocus,

 <StackPanel>
            <Image Stretch="Uniform" Source="Untitled.png"   Height="410" MouseEnter="Image_MouseEnter" MouseLeave="Image_MouseLeave"></Image>
            <TextBox Height="65"></TextBox>
 </StackPanel>

根据MSDN, UIElement。当此元素获得逻辑焦点时发生GotFocus事件。

逻辑焦点与键盘焦点不同,当路由中某个元素的IsFocused属性值从false变为true时,会引发逻辑焦点。

因此,为了通过鼠标点击来实现它,需要处理相应的鼠标按钮事件或简单地处理MouseDown并将焦点设置为发送者。

private void Image_MouseDown(object sender, MouseButtonEventArgs e)
    {
        if (sender is Image)
        {
            (sender as Image).Focus();
        }
    }

这将设置图像的IsFocused属性为true

最新更新