我创建了一个TextEditor
继承自 AvalonEdit 的自定义控件。我这样做是为了方便使用此编辑器控件使用 MVVM 和 Caliburn Micro。[为显示目的而削减]MvvTextEditor
类是
public class MvvmTextEditor : TextEditor, INotifyPropertyChanged
{
public MvvmTextEditor()
{
TextArea.SelectionChanged += TextArea_SelectionChanged;
}
void TextArea_SelectionChanged(object sender, EventArgs e)
{
this.SelectionStart = SelectionStart;
this.SelectionLength = SelectionLength;
}
public static readonly DependencyProperty SelectionLengthProperty =
DependencyProperty.Register("SelectionLength", typeof(int), typeof(MvvmTextEditor),
new PropertyMetadata((obj, args) =>
{
MvvmTextEditor target = (MvvmTextEditor)obj;
target.SelectionLength = (int)args.NewValue;
}));
public new int SelectionLength
{
get { return base.SelectionLength; }
set { SetValue(SelectionLengthProperty, value); }
}
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged([CallerMemberName] string caller = null)
{
var handler = PropertyChanged;
if (handler != null)
PropertyChanged(this, new PropertyChangedEventArgs(caller));
}
}
现在,在拥有此控件的视图中,我有以下 XAML:
<Controls:MvvmTextEditor
Caliburn:Message.Attach="[Event TextChanged] = [Action DocumentChanged()]"
TextLocation="{Binding TextLocation, Mode=TwoWay}"
SyntaxHighlighting="{Binding HighlightingDefinition}"
SelectionLength="{Binding SelectionLength,
Mode=TwoWay,
NotifyOnSourceUpdated=True,
NotifyOnTargetUpdated=True}"
Document="{Binding Document, Mode=TwoWay}"/>
我的问题是SelectionLength
(SelectionStart
但让我们现在只考虑长度,因为问题是一样的)。如果我用鼠标选择了一些东西,从视图到我的视图模型的绑定效果很好。现在,我编写了一个查找和替换实用程序,我想从后面的代码中设置SelectionLength
(在控件中具有get
并且set
可用)。TextEditor
在我的视图模型中我只是设置SelectionLength = 50
,我在视图模型中实现这个
private int selectionLength;
public int SelectionLength
{
get { return selectionLength; }
set
{
if (selectionLength == value)
return;
selectionLength = value;
Console.WriteLine(String.Format("Selection Length = {0}", selectionLength));
NotifyOfPropertyChange(() => SelectionLength);
}
}
当我设置时SelectionLength = 50
,类DependencyProperty SelectionLengthProperty
中没有更新,MvvmTextEditor
就像TwoWay
绑定到我的控件失败但使用 Snoop 没有任何迹象。我认为这只会通过绑定起作用,但事实并非如此。
我是否缺少一些简单的东西,或者我是否必须在类中设置事件处理程序MvvmTextEditor
来监听我的视图模型中的变化并更新 DP 本身[这会带来它自己的问题]?
谢谢你的时间。