绑定到属性不起作用

时间:2012-11-21 08:23:47

标签: c# wpf mvvm

这是用户控制背后的代码

 public delegate void YardSelectionChangedDelegate();
 public event YardSelectionChangedDelegate YardSelectionChanged;
 public static readonly DependencyProperty SelectedYardIdProperty =
     DependencyProperty.Register(
         "SelectedYardId",
         typeof(long),
         typeof(YardSelectorUserControl),
         new UIPropertyMetadata(null));

这是财产:

public long SelectedYardId
{
    get { return (long)GetValue(SelectedYardIdProperty); }
    set { SetValue(SelectedYardIdProperty, value); }
}

这是父窗口中的Binding:

SelectedYardId="{Binding  Path=YardId,UpdateSourceTrigger=PropertyChanged}" 

问题是属性Set永远不会工作,光标永远不会到达Set主体。 非常感谢。

2 个答案:

答案 0 :(得分:3)

这是因为绑定引擎不使用您的set或get访问器来设置或获取属性。它直接使用DependencyObject的SetValue和GetValue。为了在更改依赖项属性时触发事件,您需要在注册依赖项属性时定义回调委托,如下所示:

public static readonly DependencyProperty SelectedYardIdProperty =
    DependencyProperty.Register(
        "SelectedYardId",
        typeof(long),
        typeof(YardSelectorUserControl),
        new UIPropertyMetadata(OnSelectedYardIdChanged));

public static void OnSelectedYardIdChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
     // Action 
}

答案 1 :(得分:0)

也许您应该在模型中实现INotifyPropertyChanged,并更改“YardId”属性以在“Set”主体中引发PropertyChanged事件。