Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: XAML property declarations not being set via Setters?

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?

like image 524
ocodo Avatar asked Oct 01 '10 02:10

ocodo


1 Answers

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.

like image 139
ASanch Avatar answered Oct 30 '22 04:10

ASanch