MVVM パターンを使用して AvalonEdit を動作させようとしていますが、正確に何をすればよいかわかりません。ビジネス ロジックを実行するときにこれら 2 つの値にアクセスできるように、SelectionLength と SelectionStart を ViewModel にバインドします。
私はそのような DependencyProperties を作成し始めました:
public class MvvmTextEditor : TextEditor, INotifyPropertyChanged
{
/// <summary>
/// A bindable Text property
/// </summary>
public new string Text
{
get { return base.Text; }
set {
base.Text = value;
RaisePropertyChanged();
}
}
/// <summary>
/// A bindable SelectionStart property
/// </summary>
public new int SelectionStart
{
get { return base.SelectionStart; }
set {base.SelectionStart = value; }
}
/// <summary>
/// A bindable SelectionLength property
/// </summary>
public new int SelectionLength
{
get { return base.SelectionLength; }
set { base.SelectionLength = value; }
}
/// <summary>
/// The bindable selection start property dependency property
/// </summary>
public static readonly DependencyProperty SelectionStartProperty =
DependencyProperty.Register("SelectionStart", typeof(int), typeof(MvvmTextEditor),
new PropertyMetadata((o, args) =>
{
var target = (TextEditor)o;
target.SelectionStart = (int)args.NewValue;
}));
/// <summary>
/// The bindable selection length property dependency property
/// </summary>
public static readonly DependencyProperty SelectionLengthProperty =
DependencyProperty.Register("SelectionLength", typeof(int), typeof(MvvmTextEditor),
new PropertyMetadata((o, args) =>
{
var target = (MvvmTextEditor) o;
target.SelectionLength = (int)args.NewValue;
Debug.WriteLine(target.SelectionLength);
}));
/// <summary>
/// The bindable text property dependency property
/// </summary>
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(MvvmTextEditor),
new PropertyMetadata((o, args) =>
{
var target = (MvvmTextEditor)o;
target.Text = (string)args.NewValue;
}));
/// <summary>
/// Raises a property changed event
/// </summary>
/// <param name="property">The name of the property that updates</param>
public void RaisePropertyChanged([CallerMemberName] string caller = "")
{
var handler = PropertyChanged;
if (handler != null)
PropertyChanged(this, new PropertyChangedEventArgs(caller));
}
public event PropertyChangedEventHandler PropertyChanged;
}
TextDependencyProperty は正常に機能していますが、SelectionLength と SelectionStart は機能していません。
SelectionChanged のイベント ハンドラーを追加しました (ただし、ここで SetValue を使用して何をしているのか正確にはわかりません。
public MvvmTextEditor()
{
TextArea.SelectionChanged += TextArea_SelectionChanged;
}
void TextArea_SelectionChanged(object sender, EventArgs e)
{
SetValue(SelectionStartProperty, SelectionStart);
SetValue(SelectionLengthProperty, SelectionLength);
}
現在、選択は機能していますが、後方への選択には問題があります。この場合、SelectionStart は常に 0 です。これまでの作業がすべて正しければ、誰かが逆方向に選択した場合にインデックスと長さを正しく変換するロジックを作成します。このロジックを PropertyMetaDataDelegate に実装する必要はありますか?