是否可以将模型用作DependencyProperty
自定义控件?我想这样做是因为我想创建一个自定义控件,它基本上是一个图像抽屉,它获取名称和用于绘图的数据点列表。
像这样的东西:
模型:
public class Draw : NotificationObject
{
public Draw(string name, List<System.Drawing.PointF> data)
{
Name = name;
Data = data;
}
private string _name;
public string Name
{
get { return _name; }
set
{
if (_name != value)
{
_name = value;
RaisePropertyChanged(() => Name);
}
}
}
private List<System.Drawing.PointF> _data;
public List<System.Drawing.PointF> Data
{
get { return _data; }
set
{
if (_data != value)
{
_data = value;
RaisePropertyChanged(() => Data);
}
}
}
}
}
自定义控件:
public class MyCanvas: System.Windows.Controls.Image
{
static void itemsChangedCallBack(DependencyObject property,
DependencyPropertyChangedEventArgs args)
{
MyCanvas searchTextBox = (MyCanvas)property;
Console.WriteLine("got update");
searchTextBox.Items = (Draw)args.NewValue;
}
public static readonly DependencyProperty ItemsProperty =
DependencyProperty.Register("Items",
typeof(Draw),
typeof(MyCanvas),new PropertyMetadata(new PropertyChangedCallback(itemsChangedCallBack)));
public Draw Items
{
get { return (Draw)GetValue(ItemsProperty); }
set { SetValue(ItemsProperty, value); }
}
}
当然还有 XAML:
<myClass:MyCanvas x:Name="Canvas1" Items="{Binding drawModel,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SizX="1600" SizY="200" />
ViewModel 调用:
public class MainWindowViewModel : BaseViewModel
{
public Draw drawModel { get; set; }
public MainWindowViewModel()
{
drawModel = new Draw("first", null); // custom control is notified
}
private someFunction() //within another thread but should not matter
{
drawModel.Data = newData; // custom control should be notified but is not
}
}
我的问题是,如果我在 ViewModel 中更改 drawModel.Data (属性),我不会收到自定义控件的通知。我之前为一个简单的字符串而不是模型做过它并且它有效。它在第一次初始化 drawModel 时起作用,但如果我稍后更新 Data 属性则不起作用。