カスタムRichEditBoxには、カスタムのDependencyPropertyというテキストがあります。私の目標は、単に私のViewModelにある文字列プロパティにそのプロパティを双方向でバインドすることです。そうすれば、ViewModelの文字列を使用して、カスタムRichEditBoxにテキストを設定/取得することができます。
RichEditBox
の場合、CustomText
プロパティを拡張することができます。あなたが知っている通りRichEditBox
の文字列をDocument.SetText
とDocument.GetText
で取得または設定できます。そして、RichEditBox
というテキストの変更を聞いて、 TextChanged
イベントで聞くことができました。私は双方向バインディングCustomTextプロパティを持つCustomRichEditBox
を作成しました。次のコードを参考にしてください。
public string CustomText
{
get { return (string)GetValue(CustomTextProperty); }
set
{
SetValue(CustomTextProperty, value);
}
}
public static readonly DependencyProperty CustomTextProperty =
DependencyProperty.Register("CustomText", typeof(string), typeof(CustomRichEditBox), new PropertyMetadata(null, new PropertyChangedCallback(OnCustomTextChanged)));
private static void OnCustomTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
CustomRichEditBox rich = d as CustomRichEditBox;
if (e.NewValue != e.OldValue)
{
rich.Document.SetText(Windows.UI.Text.TextSetOptions.None, e.NewValue.ToString());
}
}
View-model
を変更する動的RichEditBox
テキストの変更を監視します。
public CustomRichEditBox()
{
this.DefaultStyleKey = typeof(RichEditBox);
this.TextChanged += CustomRichEditBox_TextChanged;
}
private void CustomRichEditBox_TextChanged(object sender, RoutedEventArgs e)
{
string value = string.Empty;
this.Document.GetText(Windows.UI.Text.TextGetOptions.AdjustCrlf, out value);
if (string.IsNullOrEmpty(value))
{
return;
}
CustomText = value;
}
コードビハインドファイルのコントロールにViewModelをバインドする場合は、次のコードを参照することができます。
Binding myBinding = new Binding();
myBinding.Source = this.DataContext;
myBinding.Path = new PropertyPath("Info");
myBinding.Mode = BindingMode.TwoWay;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
BindingOperations.SetBinding(MyEditBox, CustomRichEditBox.CustomTextProperty, myBinding);
githubにcode sampleをアップロードしました。チェックしてください。
何を試しましたか?あなたはいくつかのコードを持っていますか? –