Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wpf how to tell when databinding has finished?

I've got a custom control which has a DependencyProperty MyAnimal - I'm binding an Animal Property on my ViewModel to the MyAnimal DependencyProperty.

I've stuck a TextBox on the Control so I can trigger an Event - whenever I trigger the event the MyAnimal property has been set - however if I put a break point on the Setter of the MyAnimal property it never gets fired!

I guess I'm missing something fundamental about WPF Dependency Properties/Binding?!

And so my question is, if I can't use the Setter how can I find out when its been set? If I put if I put a break point after InitializeComponent() its null and I had a look to see if theres an Event a can hook up to - DatabindingFinished or similar? but can't see what it would be ...

Can anyone assist please?

Thanks,

Andy

public partial class ControlStrip
{
    public ControlStrip()
    {
        InitializeComponent();
    }

    public Animal MyAnimal
    {
        get
        {
            return (Animal)GetValue(MyAnimalProperty);
        }
        set
        {
            SetValue(MyAnimalProperty, value);
        }
    }

    public static readonly DependencyProperty MyAnimalProperty =
        DependencyProperty.RegisterAttached("MyAnimal", typeof (Animal), typeof (ControlStrip));

    private void TextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
    {
        var myAnimal = MyAnimal;
        MessageBox.Show(myAnimal.Name);
    }

}
like image 339
Andy Clarke Avatar asked Dec 21 '09 18:12

Andy Clarke


2 Answers

The setter methods are never called by the runtime. They go directly to the DependencyProperty. You will need to add an additional argument to your call to RegisterAttached(). There you can add a PropertyChangedCallback.

Here is some sample code:

 public static readonly DependencyProperty MyAnimalProperty =
     DependencyProperty.RegisterAttached("MyAnimal", typeof (Animal), typeof (ControlStrip), new PropertyMetadata(AnimalChanged));

 private static void AnimalChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
 {
   // Do work here
 }
like image 70
Shaun Bowe Avatar answered Oct 29 '22 18:10

Shaun Bowe


The setter is only there for your use - you actually can leave the property off entirely, since DataBinding uses the actual DependencyProperty itself, not the CLR property.

If you need to see when the property changes, you will need to specify PropertyMetadata on your dependency property, and provide a PropertyChangedCallback.

For details, I recommend reading Dependency Property Metadata.

like image 29
Reed Copsey Avatar answered Oct 29 '22 18:10

Reed Copsey