繁体   English   中英

在代码后面的依赖属性调用

[英]Dependency Property Call in code behind

我创建了一个具有某些Dependency属性的自定义UserControl。
此自定义控件托管在Window上。
当我尝试从DependecyProperty中的代码中获取值时,它不起作用。

public static readonly DependencyProperty ValueDp = DependencyProperty.Register("Value", typeof(string), typeof(MyCustomUserControl), new FrameworkPropertyMetadata(string.Empty, OutputHandler));

public string Value
{
   get { return (string)GetValue(ValueDp); }
   set { SetValue(ValueDp, value); }
}

private static void OutputHandler(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
   var temp= dependencyObject as MyCustomUserControl;
   if (temp!= null)
   {
      dependencyObject.SetValue(ValueDp,temp._conversionValue);
   }
}

在主机上,我已经放置了一个按钮,当我单击它时,我想读取DP中存储的值,但是我将始终获得DP中设置的默认值。

有什么想法我在这里做错了吗?

问候

我认为在OutputHandler方法中,您总是会丢弃分配给该属性的新值( dependencyPropertyChangedEventArgs.NewValue

正如@Alberto所说的, OldValueNewValue是保存DependencyProperty值的属性。 以上属性可以在dependencyPropertyChangedEventArgs中找到。 在您的Handler ,成员dependencyObjecttemp引用相同的对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM