我在一个肯定是 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')。