2012-09-14 101 views
2

我有以下附加属性的定义:附加属性返回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... 

我在这里做错了什么?提前致谢!

+0

你可以尝试在'StackPanel'或其他容器中包装'TextBox'并在这个元素上设置'FocusedElement'属性? –

+0

对不起,我不能。我需要在代码后面的较高级别引用'UserControl',并且不能直接访问内部元素。除非我抓取视觉树并测试所附属性,我不喜欢这样做...... – code4life

回答

0

我测试了你的代码,它适用于我,除非你在你的Dependency Property setter中省略了“public”关键字。

我假设这是一个错字,如果不是那么那就是你的问题。

+0

对不起,我在之前的文章中有一堆错别字。现在全部修好了。 – code4life

1

您的问题是GetFocusedElement在绑定实际设置之前调用(您可能在UserControl的构造函数中调用它)。如果你在Loaded事件中调用它,它应该没问题。

+0

谢谢,我会尝试一下,通过将代理附加到用户控件上的'Load'事件。我会在星期一告诉你结果! – code4life

0
local:TestFocusManager.FocusedElement="{Binding RelativeSource={RelativeSource Self}}" 

你可以得到一个对用户控件本身的引用,并公开一个给出按钮的属性。你可以用这个作为最后的手段!

顺便说一句,只要我有附加属性的问题。我一般倾向于把回调或改变类型到该对象的,我的意思不是的UIElement倾向于使用对象至少我得到一个回调,并检查什么的确切类型来作为回调的一部分

干杯

+0

我不明白你的例子如何帮助我绑定到UserControl中的元素*。它看起来更像是你的代码试图将焦点设置到'UserControl'本身,这不是我正在尝试做的...... – code4life