我有以下附加属性的定义:附加属性返回null
public class TestFocusManager
{
public static readonly DependencyProperty FocusedElementProperty =
DependencyProperty.RegisterAttached("FocusedElement",
typeof (UIElement), typeof(TestFocusManager));
public static UIElement GetFocusedElement(DependencyObject obj)
{
return (UIElement) obj.GetValue(FocusedElementProperty);
}
public static void SetFocusedElement(DependencyObject obj, UIElement value)
{
obj.SetValue(FocusedElementProperty, value);
}
}
当我尝试在我的用户控制使用它:
<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d"
xmlns:Behaviors="clr-namespace:MyLocalProject.Behaviors"
Behaviors:TestFocusManager.FocusedElement="{Binding ElementName=testElement}"
x:Class="LocalProject.TestView"
x:Name="_testView">
<TextBox x:Name="testElement" />
</UserControl>
附加属性总是返回一个空...
var result = TestFocusManager.GetFocusedElement(_testView); // <-- null...
var result2 = _testView.GetValue(TestFocusManager.FocusedElementProperty); // <-- again, null...
我在这里做错了什么?提前致谢!
你可以尝试在'StackPanel'或其他容器中包装'TextBox'并在这个元素上设置'FocusedElement'属性? –
对不起,我不能。我需要在代码后面的较高级别引用'UserControl',并且不能直接访问内部元素。除非我抓取视觉树并测试所附属性,我不喜欢这样做...... – code4life