2013-10-16 28 views
0

我的MVVM程序中有一個RichTextBox。 我想將RichTextBox.Selection屬性綁定到我的模型。 爲了實現這個任務,我創建其中包含一個RichTextBox的自定義用戶控件:在MVVM中綁定RichTextBox.Selection

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

在我的用戶等級:

// 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屬性和他的模型之間的綁定,但我不知道該怎麼做。 我想我錯過了一些東西,但我找不到什麼。

回答

0

RichTextBox.Selection不是DependancyProperty所以你不能綁定到那個。

但是對於你的設置,你只需要設置BindingModeTwoWayUserControl(ssuming模型屬性名稱是ModelTextSelection)

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

SelectionChanged方法你需要用RichTextBox.Selection

更新您 TextSelection DependancyProperty
private void RichTextBox_SelectionChanged(object sender, RoutedEventArgs e) 
    { 

     TextSelection = richTextBox.Selection; 

    } 
+0

它解決了您的問題嗎? – Nitin