WPF设置控件获得焦点FocusManager

来源:互联网 发布:002型航母 知乎 编辑:程序博客网 时间:2024/06/08 00:53

转载地址:http://www.cnblogs.com/tommy-huang/p/5175948.html


简单用法如下:

    在父类容器中通过附加属性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>
复制代码