WPF: XAML property declarations not being set via Setters?

醉酒当歌 提交于 2019-12-17 06:16:08

问题


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

e.g.

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

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.

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

Codebehind excerpt...

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... 
      }
   }
}

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

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?


回答1:


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.



来源:https://stackoverflow.com/questions/3836076/wpf-xaml-property-declarations-not-being-set-via-setters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!