首页 文章

将重点放在ControlTemplate中的控件上(第2部分)

提问于
浏览
12

我'm stumped on what must surely be one of the most common WPF requirements. I'已阅读this question但我的解决方案的实施不起作用 .

这是无视控件的标记:

<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的标记:

<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 :(没有路径);的DataItem = NULL; target元素是'CustomControl'(Name ='CCtl'); target属性是'FocusedElement'(类型'IInputElement') .

我不知道为什么会出现这个错误 . 任何指针都感激不尽,谢谢 .

2 回答

  • 12

    请尝试将此用作触发器:

    <Trigger Property="IsFocused" Value="True">
        <Setter TargetName="myTextBox" Property="FocusManager.FocusedElement" Value="{Binding ElementName=myTextBox}" />
    </Trigger>
    

    该错误告诉您它无法找到myTextBox,因为该名称不在应用FocusedElement属性的范围内 . 在这种情况下,这是在CCtl实例本身,它无法在自己的模板中看到 . 通过在模板内的某些内容上设置属性,Binding可以找到指定的元素 .

  • 0

    我可能错了,但我认为你的问题在于你的属性触发器 .

    通过将 TextBox 设置为聚焦,实际上会使Templated Parent上的 Trigger 无效,因此触发器会展开并反转设置TextBox上的焦点(因此不会聚焦它) .

相关问题