是否可以将模型作为自定义控件的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属性,则无法工作。
INotifyPropertyChanged
。 - Dan Puzey