【问题标题】:Changing focus in xaml在 xaml 中更改焦点
【发布时间】:2011-01-07 15:17:28
【问题描述】:

我在将焦点更改为 xaml 上的某个按钮时遇到问题。 我尝试执行的代码如下所示(如果满足某些条件,则应将焦点设置为按钮。奇怪的是,出于测试目的,我还更改了按钮的背景,并且每个都设置了此属性满足条件的时间。如何设置默认按钮或将焦点设置在该按钮上?

<Button.Style>
<Style TargetType="{x:Type Button}">
<Style.Triggers>
  <MultiDataTrigger>
    <MultiDataTrigger.Conditions>
      <Condition Binding="{Binding Path=SomeProperty1.Count, Converter={StaticResource IntegerToBooleanConverter}}" Value="True"/>
      <Condition Binding="{Binding Path=SomeProperty2, Converter={StaticResource NullToBoolConverter}}" Value="False"/>
      <Condition Binding="{Binding Path=SomeProperty3.Count, Converter={StaticResource IntegerToBooleanConverter}}" Value="True"/> 
    </MultiDataTrigger.Conditions>
    <Setter Property="FocusManager.FocusedElement" Value="{Binding RelativeSource={RelativeSource Self}}"/>
    <Setter Property="IsDefault" Value="True"/> 
    <Setter Property="Background" Value="Green"/>
  </MultiDataTrigger>
</Style.Triggers>

另外,我想写下 SomeProperty1 和 SomeProperty2 仅在我单击特定按钮时才设置。正如我所看到的,这些按钮具有焦点。

【问题讨论】:

    标签: wpf xaml focus multidatatrigger


    【解决方案1】:

    问题在于FocusManager.FocusedElement 仅控制FocusScope 内的本地焦点。由于Button 不是它自己的FocusScope,它没有任何效果。你需要调用Focus()方法,这需要你写一些代码。

    您可以做显而易见的事情并编写一个事件处理程序,或者您可以做非显而易见的事情并创建一个附加属性“MyFocusManager.ForceFocus”,当从 false 转换为 true 时,设置 FocusManager.FocusedElement。这是通过PropertyChangedCallback 完成的,如下所示:

    public class MyFocusManager
    {
      public static bool GetForceFocus .... // use "propa" snippet to fill this in
      public static void SetForceFocus ....
      public static DependencyProperty ForceFocusProperty = DependencyProperty.RegisterAttached("ForceFocus", typeof(bool), typeof(MyFocusManager),  new UIPropertyMetadata
        {
          PropertyChangedCallback = (obj, e) =>
          {
            if((bool)e.NewValue && !(bool)e.OldValue & obj is IInputElement)
              ((IInputElement)obj).Focus();
          }
        });
    }
    

    【讨论】:

    • 好吧,它不起作用。 PropertyChangedCallback 确实执行了,但焦点仍在另一个按钮上。
    • 在我将其他两个按钮的 Focusable 属性设置为 false 后它可以工作
    • 对不起,我的错。您需要调用Focus() 方法来更改焦点。 Focus() 方法将找到正确的范围并设置范围的FocusedElement 附加属性。请参阅我的更正答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-28
    • 1970-01-01
    • 1970-01-01
    • 2014-03-05
    • 1970-01-01
    相关资源
    最近更新 更多