DependencyProperty callback not called

2019-09-11 06:24发布

问题:

I'm currently doing an usercontrol with C#/WPF and i'm using some DependencyProperty objects.

What I want to do is when the value changes, we call a callback method to process some data... I saw that there is a PropertyChangedCallback class for this purpose, but it doesn't work..

Here's my code:

UserControl:

public partial class TimeLine : UserControl
{
    public static readonly DependencyProperty FramecountProperty = DependencyProperty.Register("FrameCount", typeof(Int32), typeof(TimeLine), new FrameworkPropertyMetadata(0, new PropertyChangedCallback(FrameCountChanged)));

    public Int32 FrameCount
    {
        get { return (Int32)this.GetValue(FramecountProperty); }
        set { this.SetValue(FramecountProperty, value); }
    }

    // More code...

    public static void FrameCountChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        // Do stuff
    }
}

xaml:

<!-- Time line container -->
<controls:TimeLine Grid.Row="2" Header="Storyboard" FrameCount="{Binding FrameCount}" />

ViewModel:

private Int32 frameCount;
public Int32 FrameCount
{
    get { return this.frameCount; }
    // this is from: https://github.com/ShyroFR/CSharp-Elegant-MVVM
    set { this.NotifyPropertyChanged(ref this.frameCount, value); }
}

public MainViewModel()
{
    this.FrameCount = 42;
}

I'm I doing it the wrong way?

Thanks for your help.

回答1:

Add Mode=TwoWay to your binding. By default binding for custom dependency properties are OneWay.



回答2:

I've found a solution, by finding the ancestor.

<controls:TimeLine Grid.Row="2" Header="Storyboard" FrameCount="{Binding Path=DataContext.FrameCount, Mode=TwoWay, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}" />

Thanks for your help!