未调用DependencyProperty回调

时间:2016-01-25 16:33:13

标签: c# wpf user-controls

我正在使用C#/ WPF进行用户控制,我正在使用一些DependencyProperty对象。

我想要做的是当值发生变化时,我们调用一个回调方法来处理一些数据......我看到有一个PropertyChangedCallback类用于此目的,但它不起作用..

这是我的代码:

用户控件:

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}" />

视图模型:

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

我是以错误的方式做的?

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

Mode=TwoWay添加到您的绑定中。默认情况下,自定义依赖项属性的绑定是OneWay。

答案 1 :(得分:0)

通过寻找祖先,我找到了解决方案。

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

感谢您的帮助!