wpf - 无法获得附加的属性(property)值(value)

标签 wpf mvvm attached-properties

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

我正在使用棱镜和MVVM创建WPF应用程序。

我试图创建我发现here的附加属性。

在我的ViewModel中,通过

var control = Keyboard.FocusedElement;

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

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

更新
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"/>

最佳答案

问题是,当我使用Keyboard.FocusedElement时,我没有得到正确的控件。当我使用它们的控件时,这可能是devexpress的事情。因此,向上遍历元素树直到我获得该控件解决了我的问题...谢谢Clemens!

关于wpf - 无法获得附加的属性(property)值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16940030/

相关文章:

c# - 如何将 X 按钮绑定(bind)到窗口的关闭按钮

mvvm - 用于添加和编辑的多个ViewModel(WPF,MVVM)

c# - 使用数据绑定(bind)访问 DataTemplate 中的 WPF 组件

c# - 如何检查 XAML 元素是否支持 AutomationId 属性

c# - 具有过滤器和自动完成功能的组合框

WPF/附加属性 - 请解释为什么它有效

c# - WPF:在附加属性中,如何等待可视化树正确加载?

silverlight - 自定义 XAML 属性

c# - 由于不兼容,无法安装 toast 通知

c# - 如何使用 C#/WPF 为 MouseEnter 和 MouseLeave 事件上的 ListBox 项目设置动画?