我創建了一個自定義的從AvalonEdit繼承的TextEditor
控件。我這樣做是爲了方便使用此編輯器控件來使用MVVM和Caliburn Micro。 [剪切下來用於顯示目的] MvvTextEditor
類是使用MVVM在WPF中綁定失敗
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本身[呈現它自身的問題]
謝謝你的時間。
我現在就試試這個,送還給你。感謝您的時間... – MoonKnight
您是否在構造函數中註冊'SelectionLengthPropertyChanged'? – MoonKnight
不,我很抱歉。您正在將其註冊到'Dependencyproperty''元數據'中。在我的例子中忘了這個。另外:嘗試直接設置值到控制。這將是我猜測的最佳方式。 –