色付きのComboBoxを含むTabItemと、その色で長方形を描画するカスタムCanvasを備えた単純なWPFウィンドウがあります。私の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は、ウィンドウの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は更新されません。私はここで何が間違っているのですか?