我有以下附加属性定义:
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>
附加属性始终返回null ...
var result = TestFocusManager.GetFocusedElement(_testView); // <-- null...
var result2 = _testView.GetValue(TestFocusManager.FocusedElementProperty); // <-- again, null...
我在这里做错了什么?提前谢谢!
答案 0 :(得分:1)
你的问题是在实际设置绑定之前调用GetFocusedElement
(你可能在UserControl的构造函数中调用它)。如果你在Loaded
事件中调用它,那应该没问题。
答案 1 :(得分:0)
我测试了你的代码,除非你在Dependency Property setter中省略了“public”关键字,否则它对我来说很好。
我认为这是一个错字,如果不是那么那就是你的问题。
答案 2 :(得分:0)
local:TestFocusManager.FocusedElement="{Binding RelativeSource={RelativeSource Self}}"
您可以获得对用户控件本身的引用,并公开一个提供按钮的公共属性。您可以将此作为最后的手段!。
顺便说一下,每当我遇到附加属性的问题时。我通常倾向于回调或将类型更改为Object的类型,我的意思是代替UIElement倾向于使用对象至少我得到一个回调并检查什么是确切类型作为回调的一部分
干杯