我有一个简单的 WPF 窗口,其中包含一个包含颜色组合框的 TabItem 和一个使用该颜色绘制矩形的自定义 Canvas。在我的 PaintCanvas 中,我有一个这样的 DependencyProperty:
class PaintCanvas : System.Windows.Controls.Canvas
{
public static readonly DependencyProperty PaintObjectProperty = DependencyProperty.Register(
"PaintObject", typeof(PaintObject), typeof(PaintCanvas), new PropertyMetadata(OnPaintObjectChanged));
public PaintObject PaintObject
{
get { return this.GetValue(PaintObjectProperty) as PaintObject; }
set
{
this.SetValue(PaintObjectProperty, value);
}
}
private static void OnPaintObjectChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
PaintCanvas canvas = (PaintCanvas)d;
// Update stuff
canvas.InvalidateVisual();
}
protected override void OnRender(DrawingContext dc)
{
base.OnRender(dc);
if (PaintObject != null)
{
dc.DrawRectangle(new SolidColorBrush(PaintObject.Color), null, new Rect(0, 0, PaintObject.Width, PaintObject.Height));
}
}
}
PaintObject 依赖属性在 xaml 中绑定到其在 PaintViewModel 中的相应属性:
<TabControl>
<TabItem DataContext="{Binding PaintViewModel}">
<StackPanel >
<ComboBox ItemsSource="{Binding Colors}" SelectedItem="{Binding Color}" />
<my:PaintCanvas Width="100" Height="100" PaintObject="{Binding PaintObject}" />
</StackPanel>
</TabItem>
</TabControl>
PaintViewModel 是 Window 的 ViewModel 中的一个属性:
class MainViewModel
{
PaintViewModel paintViewModel;
public MainViewModel()
{
paintViewModel = new PaintViewModel();
}
public PaintViewModel PaintViewModel
{
get { return paintViewModel; }
}
...
}
实际的 PaintViewModel:
class PaintViewModel : INotifyPropertyChanged
{
PaintObject paintObject;
ObservableCollection<Color> colors = new ObservableCollection<Color>();
Color currentColor;
public PaintObject PaintObject
{
get { return paintObject; }
set { paintObject = value; RaisePropertyChanged("PaintObject"); }
}
public ObservableCollection<Color> Colors
{
get { return colors; }
}
public Color Color
{
get { return currentColor; }
set {
currentColor = value;
RaisePropertyChanged("Color");
paintObject.Color = currentColor;
RaisePropertyChanged("PaintObject");
}
}
// Constructors and INotifyPropertyChanged stuff...
}
TabItem 似乎正确绑定到视图模型,因为颜色组合框可以正常工作。但是,尽管绘制对象已更新并调用了 RaisePropertyChanged("PaintObject"),但 PaintCanvas 中的 DependencyProperty 永远不会更新。我在这里做错了什么?