【问题标题】:Attached properties return null附加属性返回 null
【发布时间】: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,并且不能直接访问内部元素。除非我爬取可视化树并测试附加属性,否则我不愿意这样做......

标签: wpf attached-properties


【解决方案1】:

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

【讨论】:

  • 谢谢,然后我会尝试通过将委托附加到用户控件上的Load 事件。我会在星期一通知你结果!
【解决方案2】:

我测试了你的代码,它对我来说很好,只是你在依赖属性设置器中省略了“public”关键字。

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

【讨论】:

  • 对不起,我在上一篇文章中有很多错别字。现在都修好了。
【解决方案3】:
local:TestFocusManager.FocusedElement="{Binding RelativeSource={RelativeSource Self}}"

您可以获得对用户控件本身的引用并公开一个提供按钮的公共属性。您可以将此作为最后的手段!。

顺便说一句,每当我遇到附加属性问题时。我通常倾向于放置回调或将类型更改为 Object 的类型,我的意思是 UIElement 倾向于使用对象,至少我得到一个回调并检查作为回调的一部分的确切类型是什么

干杯

【讨论】:

  • 我不明白您的示例如何帮助我绑定到UserControl 的元素。看起来您的代码更像是试图将焦点设置到 UserControl 本身,这不是我想要做的......
猜你喜欢
  • 2012-04-29
  • 1970-01-01
  • 1970-01-01
  • 2013-05-10
  • 2019-07-17
  • 2018-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多