在控件模板中设置控件的焦点(第二部分)

13

我在一个肯定是 WPF 最常见的要求上遇到了困难。我已经阅读了这个问题,但我的解决方案的实现不起作用。

这是无样式控件的标记:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:local="clr-namespace:WpfTest">
  <Style TargetType="{x:Type local:CustomControl}">
    <Setter Property="Template">
      <Setter.Value>
        <ControlTemplate TargetType="{x:Type local:CustomControl}">
          <Border>
            <TextBox x:Name="myTextBox" />
          </Border>
          <ControlTemplate.Triggers>
            <Trigger Property="IsFocused"
                     Value="True">
              <Setter Property="FocusManager.FocusedElement"
                      Value="{Binding ElementName=myTextBox}" />
              <Setter TargetName="myTextBox"
                      Property="Background"
                      Value="Green" />
            </Trigger>
          </ControlTemplate.Triggers>
        </ControlTemplate>
      </Setter.Value>
    </Setter>
  </Style>
</ResourceDictionary>

这是包含CustomControl实例的窗口的标记:

<Window x:Class="WpfTest.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfTest"
        Title="Window1" Height="300" Width="300">

  <local:CustomControl x:Name="CCtl" />
</Window>

这是后台代码:

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
        Loaded += (RoutedEventHandler)delegate { CCtl.Focus(); };
    }
}

当Window1被加载时,文本框会变成绿色(表示触发器正在工作),但焦点仍然停留在CCtl而不是文本框上。毫无疑问,这与输出显示以下数据错误有关:

无法找到引用为'ElementName=myTextBox'的绑定源。 BindingExpression:(no path); DataItem=null; target element is 'CustomControl' (Name='CCtl'); target property is 'FocusedElement' (type 'IInputElement')。

我不知道为什么会出现这个错误。非常感谢您提供任何指导。谢谢。
2个回答

14

尝试使用这个作为您的触发器:

<Trigger Property="IsFocused" Value="True">
    <Setter TargetName="myTextBox" Property="FocusManager.FocusedElement" Value="{Binding ElementName=myTextBox}" />
</Trigger>
错误提示您无法定位myTextBox,因为应用FocusedElement属性的范围内不存在该名称。在此情况下,这是在CCtl实例本身上,它无法看到自己的模板内部。通过在模板内设置属性,绑定可以找到命名的元素。

0

我可能错了,但我认为你的问题出在你的属性触发器上。

通过将你的TextBox设置为聚焦状态,你实际上使得模板父级上的Trigger无效,因此触发器会被取消并且反转以取消TextBox上的聚焦状态(因此失去聚焦状态)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接