【问题标题】:Two-way binding to a "custom" RichEditBox's custom properties in ViewModel (UWP)在 ViewModel (UWP) 中双向绑定到“自定义”RichEditBox 的自定义属性
【发布时间】:2017-04-07 19:18:58
【问题描述】:

在 UWP 应用中,当您需要在 ViewModel 中向/从它传递文本时,RichEditBox 控件本身不能很好地与基于 MVVM 的设计模式一起工作,因此我创建了它的自定义版本。

在自定义 RichEditBox 中,我有一个名为 Text 的自定义 DependencyProperty。我的目标只是将该属性双向绑定到位于我的 ViewModel 中的字符串属性。这样我就可以使用 ViewModel 中的字符串在我的自定义 RichEditBox 中设置/获取文本。如果我采用 XAML 方法,这很容易。但是,如何在我的代码隐藏文件中完成此操作?我尝试过但未能成功。谢谢。

【问题讨论】:

  • 你尝试了什么?你有一些代码可以开始吗?

标签: c# xaml data-binding uwp


【解决方案1】:

在自定义 RichEditBox 中,我有一个名为 Text 的自定义 DependencyProperty。我的目标只是将该属性双向绑定到位于我的 ViewModel 中的字符串属性。这样我就可以使用 ViewModel 中的字符串来设置/获取自定义 RichEditBox 中的文本。

对于您的方案,您可以为您的自定义 RichEditBox 扩展一个 CustomText 属性。如您所知,您可以通过Document.SetTextDocument.GetText 方法获取或设置RichEditBox 的字符串。然后您可以通过以下方式收听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());
        }
  }

监控RichEditBox文字的变化动态修改View-model

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);

我已将code sample 上传到 github。请检查。

【讨论】:

  • 对不起,我迟到了回复。谢谢。但是,我认为你错过了我的观点。我正在尝试从我的代码隐藏文件中绑定到控件,如帖子中所述...我明确表示通过 XAML 进行绑定是没有问题的。再次感谢!
  • 我已经编辑了我的答案。如果您从后面的代码将 ViewModel 绑定到控件,它也可以很好地工作。是你吗?
猜你喜欢
  • 2016-06-10
  • 2018-09-03
  • 1970-01-01
  • 2019-07-23
  • 2015-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多