【发布时间】:2014-07-12 17:22:50
【问题描述】:
我创建了一个继承自 AvalonEdit 的自定义 TextEditor 控件。我这样做是为了方便使用此编辑器控件使用 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(在TextEditor 控件中提供get 和set)。在我的视图模型中,我只是设置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 本身 [这提出了它自己的问题] ?
感谢您的宝贵时间。
【问题讨论】:
标签: c# wpf mvvm binding avalonedit