题
我似乎已经遇到了一个路障。我们使用MVVM与棱镜和有需要的墨迹画布视图。我已经创建正从我的ViewModel的视图结合的StrokeCollection中。我能够从我的视图模型设置的集合,但同时用户绘制的更改不会上来的视图模型。有没有一种方法,使这项工作?
我在我的ViewModel属性如下:
private StrokeCollection _strokes;
public StrokeCollection Signature
{
get
{
return _strokes;
}
set
{
_strokes = value;
OnPropertyChanged("Signature");
}
}
下面是我的XAML绑定行:
<InkCanvas x:Name="MyCanvas" Strokes="{Binding Signature, Mode=TwoWay}" />
出于某种原因,显然InkCanvas从未通知任何变化的视图模型。
解决方案
你的方法的问题是,你承担InkCanvas
创建StrokeCollection
。它没有 - 它只是增加了,并从中删除项目。而如果集合不可用(即是null
),绑定将失败,InkCanvas
不会做的任何的吧。所以:
- 您需要创建一个单一的
StrokeCollection
- 您需要承担的集合的内容会发生变化,而不是集合本身 醇>
实施例的代码:
public class ViewModel : INotifyPropertyChanged
{
private readonly StrokeCollection _strokes;
public ViewModel()
{
_strokes = new StrokeCollection();
(_strokes as INotifyCollectionChanged).CollectionChanged += delegate
{
//the strokes have changed
};
}
public event PropertyChangedEventHandler PropertyChanged;
public StrokeCollection Signature
{
get
{
return _strokes;
}
}
private void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
和XAML:
<InkCanvas Strokes="{Binding Signature}"/>
其他提示
StrokeCollection中类有一个名为“StrokesChanged”当你画在视图的东西,总是触发的事件。这一事件包含笔触更新的集合。
XAML:
<Grid>
<InkCanvas Strokes="{Binding Signature}"/>
</Grid>
VM:
public class TestViewModel : INotifyPropertyChanged
{
public StrokeCollection Signature { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
public TestViewModel()
{
Signature = new StrokeCollection();
Signature.StrokesChanged += Signature_StrokesChanged;
}
void Signature_StrokesChanged(object sender, StrokeCollectionChangedEventArgs e)
{
//PUT A BREAKPOINT HERE AND CHECK
Signature = (System.Windows.Ink.StrokeCollection)sender;
}
}
希望它能帮助!
不隶属于 StackOverflow