WPF設置控件獲得焦點FocusManager


 

簡單用法如下:

    在父類容器中通過附加屬性FocusManager.FocusedElement來綁定需要強制獲得焦點的控件,用法如下:

    <Grid FocusManager.FocusedElement="{Binding ElementName=btn}">
        <Button x:Name="btn" Content="1234"/>

    </Grid>

需要注意的是:當控件使用Style或者Template重寫了控件的結構時,這樣設置可能會無效,此時需要進入到Template中去設置

     可以查看例子:

 1 <Window x:Class="FocusManagerDemo.MainWindow"
 2         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 3         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 4         Title="MainWindow" Height="350" Width="525">
 5     <Grid>
 6         <!--需要測試外層Button時,可以去掉注釋,同時注意,同一時刻內只有一個控件能獲得焦點<Grid FocusManager.FocusedElement="{Binding ElementName=btn}">-->
 7             <Button x:Name="btn" Content="1234"/>
 8         <Grid>
 9             <TextBox x:Name="txt" Text="abc" Margin="106,73,97,145">
10                 <TextBox.Style>
11                     <Style TargetType="TextBox">
12                         <Setter Property="Template">
13                             <Setter.Value>
14                                 <ControlTemplate TargetType="TextBox">
15                                     <Grid FocusManager.FocusedElement="{Binding ElementName=btn123}">
16                                         <Button x:Name="btn123" Content="123" Margin="10"/>
17                                     </Grid>
18                                 </ControlTemplate>
19                             </Setter.Value>
20                         </Setter>
21                     </Style>
22                 </TextBox.Style>
23             </TextBox>
24         </Grid>
25     </Grid>
26 </Window>
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM