【发布时间】:2012-09-14 14:23:32
【问题描述】:
我有以下附加属性定义:
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...
我在这里做错了什么?提前致谢!
【问题讨论】:
-
您可以尝试将
TextBox包装在StackPanel或其他容器中并在此元素上设置FocusedElement属性吗? -
对不起,我不能。我需要在代码后面的更高级别引用
UserControl,并且不能直接访问内部元素。除非我爬取可视化树并测试附加属性,否则我不愿意这样做......