如何在UWP中数据绑定到RichEditBox的纯文本值?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在UWP中数据绑定到RichEditBox的纯文本值?相关的知识,希望对你有一定的参考价值。

使用UWP中的正常TextBox,您可以数据绑定到Text属性,并轻松地从ViewModel获取或设置值。 RichEditBox虽然没有数据绑定的Text属性;相反,你必须使用ITextDocument interface属性公开的Document并使用各种方法来获取和设置文本。

如何将纯文本数据绑定到ViewModel中的某些内容?

答案

可以使用自定义RichEditBoxattached property的纯文本进行数据绑定。此附加属性处理富文本和文档纯文本之间的转换。

下面是一个示例XAML页面,代码隐藏和ViewModel,显示附加属性的用法:

XAML

将其复制为项目中新页面的内容

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
  <StackPanel Margin="30">
    <RichEditBox local:RichEditBoxExtension.PlainText="{Binding PlainText,
      Mode=TwoWay}" x:Name="richedit"/>
    <Button Content="Bold selection" Click="MakeBold"/>
    <Button Content="Change plain text (view model)" Click="ChangeText"/>
    <Button Content="Change rich text (control property)" Click="ChangeRichText"/>
    <TextBlock Text="PlainText property is..." />
    <TextBlock Text="{Binding PlainText, Mode=OneWay}" />
  </StackPanel>
</Grid>

Code behind

这假设你使用默认的MainPage.xaml.cs;根据需要更改构造函数名称

public MainPage()
{
  InitializeComponent();
  DataContext = model = new ViewModel();
  model.PlainText = "Hello, world";
}

private void ChangeText(object sender, RoutedEventArgs e)
{
  model.PlainText = "Here is some plain text";
}

private void ChangeRichText(object sender, RoutedEventArgs e)
{
  richedit.Document.SetText(TextSetOptions.None, "Here is some rich text");
  var selection = richedit.Document.Selection;
  selection.StartPosition = 8;
  selection.EndPosition = 12;
  selection.CharacterFormat.Underline = UnderlineType.Single;
  selection.MoveStart(TextRangeUnit.Word, 1);
  selection.Expand(TextRangeUnit.Word);
  selection.CharacterFormat.Weight = FontWeights.Bold.Weight;
}

private void MakeBold(object sender, RoutedEventArgs e)
{
  richedit.Document.Selection.CharacterFormat.Weight = FontWeights.Bold.Weight;
}

ViewModel

没什么特别的;只是一个字符串属性。您可以将其放在自己的文件中,或将其粘贴到主代码隐藏文件中。

public class ViewModel : INotifyPropertyChanged
{
  public event PropertyChangedEventHandler PropertyChanged;
  string plainText;
  public string PlainText
  {
    get { return plainText; }
    set
    {
      plainText = value;
      RaisePropertyChanged();
    }
  }

  void RaisePropertyChanged([CallerMemberName] string propertyName = "")
  {
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  }
}

到目前为止,没什么特别的RichEditBox使用附加属性RichEditBoxExtension.PlainText并将其绑定到ViewModel属性PlainText。页面上还有另一个TextBlock来显示PlainText属性的当前值,以及一些操作文本的按钮。

RichEditBoxExtension.PlainText的实现非常简单,但由于依赖属性基础结构和避免无限属性更新的需要(需要更改富文本触发纯文本,触发富文本,因此需要相当数量的代码)触发纯文本,依此类推)。

Attached property

这可以在自己的文件中,也可以再次粘贴到代码隐藏文件中。

public class RichEditBoxExtension
{
  // Standard attached property. It mimics the "Text" property of normal text boxes
  public static readonly DependencyProperty PlainTextProperty =
    DependencyProperty.RegisterAttached("PlainText", typeof(string),
    typeof(RichEditBoxExtension), new PropertyMetadata(null, OnPlainTextChanged));

  // Standard DP infrastructure
  public static string GetPlainText(DependencyObject o)
  {
    return o.GetValue(PlainTextProperty) as string;
  }

  // Standard DP infrastructure
  public static void SetPlainText(DependencyObject o, string s)
  {
    o.SetValue(PlainTextProperty, s);
  }

  private static void OnPlainTextChanged(DependencyObject o, 
    DependencyPropertyChangedEventArgs e)
  {
    var source = o as RichEditBox;
    if (o == null || e.NewValue == null)
      return;

    // This attaches an event handler for the TextChange event in the RichEditBox,
    // ensuring that we're made aware of any changes
    AttachRichEditBoxChangingHelper(o);

    // To avoid endless property updates, we make sure we only change the RichText's 
    // Document if the PlainText was modified (vs. if PlainText is responding to 
    // Document being modified)
    var state = GetState(o);
    switch (state)
    {
      case RichEditChangeState.Idle:
        var text = e.NewValue as string;
        SetState(o, RichEditChangeState.PlainTextChanged);
        source.Document.SetText(Windows.UI.Text.TextSetOptions.None, text);
        break;

      case RichEditChangeState.RichTextChanged:
        SetState(o, RichEditChangeState.Idle);
        break;

      default:
        Debug.Assert(false, "Unknown state");
        SetState(o, RichEditChangeState.Idle);
        break;
    }
  }

  #region Glue

  // Trivial state machine to determine who last changed the text properties
  enum RichEditChangeState
  {
    Idle,
    RichTextChanged,
    PlainTextChanged,
    Unknown
  }

  // Helper class that just stores a state inside a textbox, determining
  // whether it is already being changed by code or not
  class RichEditChangeStateHelper
  {
    public RichEditChangeState State { get; set; }
  }

  // Private attached property (never seen in XAML or anywhere else) to attach
  // the state variable for us. Because this isn't used in XAML, we don't need
  // the normal GetXXX and SetXXX static methods.
  static readonly DependencyProperty RichEditChangeStateHelperProperty =
    DependencyProperty.RegisterAttached("RichEditChangeStateHelper",
    typeof(RichEditChangeStateHelper), typeof(RichEditBoxExtension), null);

  // Inject our state into the textbox, and also attach an event-handler
  // for the TextChanged event.
  static void AttachRichEditBoxChangingHelper(DependencyObject o)
  {
    if (o.GetValue(RichEditChangeStateHelperProperty) != null)
      return;

    var richEdit = o as RichEditBox;
    var helper = new RichEditChangeStateHelper();
    o.SetValue(RichEditChangeStateHelperProperty, helper);

    richEdit.TextChanged += (sender, args) =>
    {
      // To avoid re-entrancy, make sure we're not already changing
      var state = GetState(o);
      switch (state)
      {
        case RichEditChangeState.Idle:
          string text = null;
          richEdit.Document.GetText(Windows.UI.Text.TextGetOptions.None, out text);
          if (text != GetPlainText(o))
          {
            SetState(o, RichEditChangeState.RichTextChanged);
            o.SetValue(PlainTextProperty, text);
          }
          break;

        case RichEditChangeState.PlainTextChanged:
          SetState(o, RichEditChangeState.Idle);
          break;

        default:
          Debug.Assert(false, "Unknown state");
          SetState(o, RichEditChangeState.Idle);
          break;
      }
    };
  }

  // Helper to set the state managed by the textbox
  static void SetState(DependencyObject o, RichEditChangeState state)
  {
    (o.GetValue(RichEditChangeStateHelperProperty) 
      as RichEditChangeStateHelper).State = state;
  }

  // Helper to get the state managed by the textbox
  static RichEditChangeState GetState(DependencyObject o)
  {
    return (o.GetValue(RichEditChangeStateHelperProperty) 
      as RichEditChangeStateHelper).State;
  }
  #endregion
}

附加属性基本上做了两件事,但是有很多样板代码和状态机器围绕它:

  1. PlainText附加属性更改时,它使用RichEditBox用纯文本更新source.Document.SetText(TextSetOptions.None, text)
  2. RichEditBox文本发生变化(包括富文本更改)时,它会使用PlainText然后richEdit.Document.GetText(TextGetOptions.None, out text)更新o.SetValue(PlainTextProperty, text)附加属性。

请注意,此基本方法可用于数据绑定您要基于实际数据可绑定属性计算的其他“派生”属性。

以上是关于如何在UWP中数据绑定到RichEditBox的纯文本值?的主要内容,如果未能解决你的问题,请参考以下文章

RichEditBox (UWP) 在设置 Rtf 文本时忽略字体和前景

uwp - RichEditBox - 滚动至光标位置,解决行数超出后设置颜色滚动条回滚顶部的问题

在 RichEditBox 中使用控制器进行文本选择

有没有办法在uwp应用程序中更改TextBox的行高?

在uwp中向数据网格添加新行时如何自动开始编辑?

UWP 数据绑定:如何将按钮命令设置为 DataTemplate 中的父 DataContext