【问题标题】:Bind RichTextBox.Selection in MVVM在 MVVM 中绑定 RichTextBox.Selection
【发布时间】:2013-10-16 18:25:03
【问题描述】:

我的 MVVM 程序中有一个 RichTextBox。 我想将 RichTextBox.Selection 属性绑定到我的模型。 为了完成这个任务,我创建了一个包含 RichTextBox 的自定义 UserControl:

<UserControl x:Class="MyProject.Resources.Controls.CustomRichTextBox"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <RichTextBox x:Name="RichTextBox" SelectionChanged="RichTextBox_SelectionChanged"/>
</UserControl>

在我的 UserControl 类中:

// Selection property
public static readonly DependencyProperty TextSelectionProperty =
    DependencyProperty.Register("TextSelection", typeof(TextSelection),
    typeof(CustomRichTextBox));


[Browsable(true)]
[Category("TextSelection")]
[Description("TextSelection")]
[DefaultValue("null")]
public TextSelection TextSelection
{
    get { return (TextSelection)GetValue(TextSelectionProperty); }
    set { SetValue(TextSelectionProperty, value); }
}

用法是:

<ResourcesControls:CustomRichTextBox TextSelection="{Binding ModelTextSelection}"/>

我的模型上有这个属性:

private TextSelection _TextSelection;
public TextSelection TextSelection
{
    get { return _TextSelection; }
    set { _TextSelection = value; }
}

我想在我的模型中获取 RichTextBox.Selection 属性,但 TextSelection 始终为空。 我知道我缺少 RichTextBox.Selection 属性和他的模型之间的绑定,但我不知道该怎么做。 我想我遗漏了一些东西,但我找不到什么。

【问题讨论】:

    标签: wpf mvvm richtextbox selection


    【解决方案1】:

    RichTextBox.Selection 不是 DependancyProperty,所以你不能绑定到它。

    但是对于您的设置,您只需在您的UserControl 上将BindingMode 设置为TwoWay(假设您的模型属性名称是ModelTextSelection)

       <ResourcesControls:CustomRichTextBox TextSelection="{Binding ModelTextSelection, Mode=TwoWay}"/>
    

    SelectionChanged 方法中,您需要使用RichTextBox.Selection 更新您的TextSelection DependancyProperty

        private void RichTextBox_SelectionChanged(object sender, RoutedEventArgs e)
        {
    
           TextSelection = richTextBox.Selection;
    
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-20
      • 2016-03-16
      • 1970-01-01
      • 2014-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多