我目前正在使用一个Window(带有ViewModel)和自己的UserControl的MVVM项目上工作。 .xaml文件中的UserControl几乎为空,因为它的所有功能均来自代码后方,后者可绘制不同的形状。我想将ViewModel的属性绑定到UserControl中的DependencyProperty,但是无论我做什么,我都无法使其正常工作。我在这里和其他网站上都读了很多答案,并注意到UserControl的DataContext可能有问题,但是无论如何我最终都无法解决问题。我在ViewModel中引发PropertyChanged事件的方式是正确的。我可以成功地将属性绑定到其他控件(例如TextBoxes等),但不能绑定到我的控件。如果您能向我解释为什么它不起作用以及如何解决该问题,将不胜感激。问候!
MainWindow.xaml绑定:
<Grid Margin="10">
<local:FretboardControl Grid.Row="0" Fretboard="{Binding CurrentFretboard, Mode=TwoWay}"/>
</Grid>
FretboardControl.xaml:
<UserControl ...>
<Grid>
<TextBlock Text="{Binding Path=Fretboard, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=local:FretboardControl}}"/>
//the TextBlock above is just a test
<Canvas.../>
</Grid>
</UserControl>
FretboardControl.xaml.cs(隐藏代码):
public static readonly DependencyProperty FretboardProperty = DependencyProperty.Register
(nameof(Fretboard), typeof(Fretboard), typeof(FretboardControl), new PropertyMetadata(new Fretboard(), PropertyChangedCallback));
public Fretboard Fretboard {
get {
return GetValue(FretboardProperty) as Fretboard;
}
set {
SetValue(FretboardProperty, value);
}
}
protected static void PropertyChangedCallback(DependencyObject o, DependencyPropertyChangedEventArgs e) {
//breakpoint here. It is reached only once during runtime:
//at start, when the default value is inserted
if (o is FretboardControl) {
(o as FretboardControl).RefreshFretboard();
}
}
答案 0 :(得分:0)
好吧,所以显然我很可能找到了问题的根源。我的CurrentFretboard设置程序引发了PropertyChanged事件,但我没有更改对象本身的引用。该对象已被修改,但仍然是相同的对象。我以为这没关系,无论如何都会将其发送到绑定,但是看起来只有在更改引用的情况下才调用PropertyChangedCallback。我想我可以替换每个集合上的引用,或者只听UserControl中已经存在的PropertyChanged事件。感谢您的帮助!