WPF:未通过 Setter 设置 XAML 属性声明? [英] WPF: XAML property declarations not being set via Setters?

查看:30
本文介绍了WPF:未通过 Setter 设置 XAML 属性声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 WPF 应用程序,我在代码隐藏中使用依赖属性,我想通过 XAML 声明设置它.

I have a WPF application where I'm using dependency properties in codebehind which I want to set via XAML declarations.

例如

<l:SelectControl StateType="A" Text="Hello"/>

所以在这个例子中,我有一个名为 SelectControlUserControl,它有一个名为 StateType 的属性,它操作它的 setter 中的一些其他属性.

So in this example I have a UserControl called SelectControl, which has a property called StateType which manipulate some other properties in it's setter.

为了帮助说明问题,我在示例中放置了另一个名为 Text 的属性,请继续阅读,我将进一步解释.

To help illustrate the problem, I've put another property called Text in the example, read on and I'll explain further.

代码隐藏摘录...

public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(String), typeof(SelectControl));

public String Text
{
  get { return (String)GetValue(TextProperty); }
  set { SetValue(TextProperty, value); }
}

public static readonly DependencyProperty StateTypeProperty = DependencyProperty.Register("StateType", typeof(String), typeof(SelectControl));

public String StateType
{
  get { return (String)GetValue(StateTypeProperty) }
  set
    {
      switch (value)
      {
        case "A":
          AnotherPropertyBoolean = true;
          break;
        case "B":
          AnotherPropertyBoolean = false;
          break;
       default:
         // this is only an example... 
      }
   }
}

现在,如果我在 setter 上设置断点(对于 StateTypeText),结果是它永远不会被执行.

Now, if I set a breakpoint on the setter (for either StateType or Text), it turns out it's never executed.

但是为Text声明的值,即Hello"出现在它的数据绑定TextBox中,当然我将另一个文本控件绑定到StateType的价值我也能看到.

However values declared for Text, i.e. "Hello" appears in it's data bound TextBox, and of course it I bind another text control to StateType's value I can see that too.

有人知道发生了什么吗?

Does anyone know what's happening?

推荐答案

依赖属性的CLR 包装器"只有在通过代码完成时才会被调用.XAML 取决于 DependencyProperty.Register(...) 调用中指定的名称.因此,不要像上面那样为您的依赖属性扩展"setter 的逻辑,只需将您的自定义逻辑放在 PropertyChangedCallback 函数.

The "CLR-wrappers" for dependency properties only get called when done through code. XAML depends on the name specified in the DependencyProperty.Register(...) call. So, instead of "extending" the logic of the setter for your dependency property like you did above, just put your custom logic in a PropertyChangedCallback function.

这篇关于WPF:未通过 Setter 设置 XAML 属性声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆