Chr*_*ard 12 wpf xaml focus controltemplate focusmanager
我对那些肯定是最常见的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>
Run Code Online (Sandbox Code Playgroud)
这是包含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>
Run Code Online (Sandbox Code Playgroud)
这是代码隐藏的代码:
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
Loaded += (RoutedEventHandler)delegate { CCtl.Focus(); };
}
}
Run Code Online (Sandbox Code Playgroud)
加载Window1时,文本框变为绿色(表示触发器有效)但焦点仍然是CCtl而不是文本框.毫无疑问,这与显示以下数据错误的输出有关:
无法找到引用'ElementName = myTextBox'的绑定源.BindingExpression :(没有路径); 的DataItem = NULL; target元素是'CustomControl'(Name ='CCtl'); target属性是'FocusedElement'(类型'IInputElement').
我不知道为什么会出现这个错误.任何指针都感激不尽,谢谢.
Joh*_*wen 12
请尝试将此用作触发器:
<Trigger Property="IsFocused" Value="True">
<Setter TargetName="myTextBox" Property="FocusManager.FocusedElement" Value="{Binding ElementName=myTextBox}" />
</Trigger>
Run Code Online (Sandbox Code Playgroud)
该错误告诉您它无法找到myTextBox,因为该名称不在应用FocusedElement属性的范围内.在这种情况下,这是在CCtl实例本身,它无法在自己的模板中看到.通过在模板内的某些内容上设置属性,Binding可以找到指定的元素.