RichTextBoxにバインド
9015 ワード
ほぼ元のままですがちょっとだけ変えました。XamlSource → InlinesXaml
自分で使うのに Section とか Paragraph を渡す必要がなかったので Inlines だけ渡すようにカスタマイズ。
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
namespace test
{
public static class RichTextBoxBinder
{
private const string _XAML_BEGIN = @"<Section xml:space=""preserve"" HasTrailingParagraphBreakOnPaste=""False"" xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""><Paragraph>";
private const string _XAML_END = @"</Paragraph></Section>";
#region InlinesXaml ----------------------------------------------------
#region RichTextBox attached properties
public static readonly DependencyProperty InlinesXamlProperty =
DependencyProperty.RegisterAttached(
"InlinesXaml",
typeof(string),
typeof(RichTextBox),
new PropertyMetadata(OnInlinesXamlPropertyChanged));
private static void OnInlinesXamlPropertyChanged(
DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
var rtb = d as RichTextBox;
if (rtb == null) throw new ArgumentException(
"Expected a dependency object of type RichTextBox.", "d");
string xaml = null;
if (e.NewValue != null)
{
xaml = e.NewValue as string;
if (xaml == null) throw new ArgumentException("Expected a value of type string.", "e.NewValue");
}
// Set the xaml and reset selection
//rtb.Xaml = xaml ?? string.Empty;
rtb.Xaml = (xaml == null) ? string.Empty : _XAML_BEGIN + xaml + _XAML_END;
rtb.Selection.Select(rtb.ContentStart, rtb.ContentStart);
}
#endregion
public static void SetInlinesXaml(this RichTextBox rtb, string xaml)
{
rtb.SetValue(InlinesXamlProperty, xaml);
}
public static string GetInlinesXaml(this RichTextBox rtb)
{
return (string)rtb.GetValue(InlinesXamlProperty);
}
#endregion InlinesXaml -------------------------------------------------
}
}
Xaml側
<RichTextBox local:RichTextBoxBinder.InlinesXaml="{Binding HogeXaml}" />
バインドされる側
public string HogeXaml
{
get {
var xaml = @"あいうえお<LineBreak />"
+ @"<Span Foreground=""Red"">あいうえお</Span><LineBreak />"
+ @"さしすせそ";
return xaml;
}
}
Author And Source
この問題について(RichTextBoxにバインド), 我々は、より多くの情報をここで見つけました https://qiita.com/sk_3122/items/ca357ee11fabcc046f3c著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .