我的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属性和他的模型之间的绑定,但我不知道如何做到这一点。我想我错过了什么,但我找不到什么。
发布于 2013-10-16 18:25:04
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;
}https://stackoverflow.com/questions/19399530
复制相似问题