【问题标题】:cannot get attached property value无法获取附加属性值
【发布时间】:2013-06-05 12:31:45
【问题描述】:

您好,我希望我能在这里找到一些帮助...

我正在使用 prism 和 MVVM 创建一个 WPF 应用程序。

我正在尝试创建一个我发现的附加属性here

在我的 ViewModel 中,我通过

获得了焦点元素
var control = Keyboard.FocusedElement;

那我做

string value = ExtraTextBehaviourObject.GetExtraText(control as UIElement);

但返回的值始终为空...谁能指出我正确的方向???

更新

public class ExtraTextBehaviourObject : DependencyObject
    {
        //Declare the dependency property
        public static readonly DependencyProperty ExtraTextProperty;

        static ExtraTextBehaviourObject()
        {
            //register it as attached property
            ExtraTextProperty = DependencyProperty.RegisterAttached("ExtraText", typeof(string),
                                                                    typeof(ExtraTextBehaviourObject));
        }

        //static function for setting the text
        public static void SetExtraText(UIElement uiElement, string value)
        {
            if (uiElement != null)
            {
                uiElement.SetValue(ExtraTextProperty, value);
            }
        }

        //static function for getting the text
        public static string GetExtraText(UIElement uiElement)
        {
            if (uiElement != null)
            {
                return (string)uiElement.GetValue(ExtraTextProperty);
            }
            return "";
        }
    }

在 XAML 中设置代码

<dxe:TextEdit Text="{Binding Path=Customer.Comments, Mode=TwoWay}" AcceptsReturn="True" VerticalContentAlignment="Top"
                                  HorizontalAlignment="Stretch" VerticalAlignment="Stretch"  Behaviors:ExtraTextBehaviourObject.ExtraText="HelloExtraText"
                                  ScrollViewer.CanContentScroll="True" ScrollViewer.VerticalScrollBarVisibility="Auto"/>

【问题讨论】:

  • 您或许还应该发布您的属性的实现。
  • 感谢您的回复...我刚刚更新了“设置”代码
  • 嗯,为什么你的课程来自DependencyObject?由于您使用的是UIElement.GetValue()UIElement.SetValue(...),因此不需要。
  • SetExtraText 永远不会被调用...这可能是问题...但是为什么呢?
  • 在 XAML 中设置依赖属性时,WPF 不会调用 C# setter 方法。因此,未调用 SetExtraText 的事实并不意味着未设置属性值。无论如何,您确定Keyboard.FocusedElement 返回的元素是您所期望的吗?

标签: wpf mvvm attached-properties


【解决方案1】:

问题是我在使用 Keyboard.FocusedElement 时没有得到正确的控制。当我使用他们的控件时,这可能是 devexpress 的事情。所以向上遍历元素树直到我得到那个控制解决了我的问题......谢谢克莱门斯!

【讨论】:

    【解决方案2】:

    只是一个额外的想法:您可以让 WPF 为您完成,而不是自己手动遍历树。使用FrameworkPropertyMetadataOptions.Inherits 标记您的附加属性现在,您设置附加属性的初始控件的所有子级都可以检索该值。 例如

    <Grid MyService.MyProperty="True">
       <TextBox .../>
    
    
    var txt = aSender as TextBox;
    var val = MyService.GetMyProperty(txt);
    

    Inherits GetMyProperty 将返回 true,因为它“继承”了他的父 Grid 的值,当然没有继承该值将是 false(不是 null,因为它是一种值类型)。

    DataContext 例如也是一个继承的依赖属性。

    【讨论】:

      猜你喜欢
      • 2016-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-28
      • 1970-01-01
      • 1970-01-01
      • 2016-11-21
      • 1970-01-01
      相关资源
      最近更新 更多