Focus image does not work for first time on Textbo

2019-08-02 18:56发布

问题:

i want to show a focus image around a text box when it got focus. so i create following style

<Style x:Key="TextBoxFocusVisualStyle">
            <Setter Property="Control.Template">
                <Setter.Value>
                    <ControlTemplate>
                        <Image Source="/WPFApp;component/Resources/txtFocus.png"  Stretch="Fill"  Margin="-8,-6,-8,-6"/>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

and in window xaml file i used this style as following

<TextBox  Grid.Column="1" Height="34" Margin="186,48,0,0" Name="txtEmailId" VerticalAlignment="Top" KeyboardNavigation.TabIndex="0" MaxWidth="293" HorizontalAlignment="Left" Width="293" Text="" FocusVisualStyle="{DynamicResource TextBoxFocusVisualStyle}"/>

but problem is that it does not work during loading. When window load then initially focus is on that textbox and at that time it does not show the image .However when i navigate to other textbox (and other control) then it show focus image. and finally when i focus return to that textbox then it display the focus image

so problem is that it does not show focus image first time on when window loaded. Please suggest that where i am wrong.

回答1:

Consider that FocusVisualStyle applies to a control only when focused by keyboard (TAB key).

This is different from the logical focus that you obtain for example using

 Control.SetFocus()

For an overview on Focus have a look at

http://msdn.microsoft.com/en-us/library/aa969768.aspx

A possible workaround for your problem is work with DependencyProperty IsFocused an use Style instead of FocusVisualStyle

<Style x:Key="TextBoxStyle" TargetType="{x:Type Control}">
        <Style.Triggers>
            <Trigger Property="IsFocused" Value="True">
                <Setter Property="Control.Template">
                    <Setter.Value>
                        <ControlTemplate>
                            <Image  Stretch="Fill"  Margin="-8,-6,-8,-6" Source="/WPFApp;component/Resources/txtFocus.png" />
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Trigger>
        </Style.Triggers>
    </Style>

And then in the main Window

<TextBox  Grid.Column="1" Height="34" Margin="186,48,0,0" Name="txtEmailId" 
     VerticalAlignment="Top" KeyboardNavigation.TabIndex="0" MaxWidth="293" 
                  HorizontalAlignment="Left" Width="293" Text="" 
                  Style="{DynamicResource TextBoxFocusVisualStyle}" Background="White" />

Hope this heps