LoginSignup
1
1

More than 1 year has passed since last update.

RichTextBoxにバインド

Last updated at Posted at 2012-11-15

転載元:http://stackoverflow.com/questions/6475775/how-do-i-bind-string-in-xaml-format-to-xaml-property-of-richtextbox-in-silverl

ほぼ元のままですがちょっとだけ変えました。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;
    }
}

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1