none
richtextbox problems RRS feed

  • Question

  •  

    contact_notes.Document = row["notes"].ToString();

     

    i have error for the above code...  contact_notes is the richtextbox...

     

    Error 1 Cannot implicitly convert type 'string' to 'System.Windows.Documents.FlowDocument' ....

    Sunday, January 6, 2008 6:15 AM

Answers

  • Here is an example of how to add image to the RichTextBox:

    Code Block
    <Window x:Class="MiscellaneousAnswers.AddImageToRtbDemo"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="AddImageToRtbDemo" Height="300" Width="300">
      <DockPanel>
        <Button DockPanel.Dock="Top" Width="120" Height="30" Name="btn" Content="Insert Image"/>
        <RichTextBox Name="rtb"/>
      </DockPanel>
    </Window>
    namespace MiscellaneousAnswers
    {
        public partial class AddImageToRtbDemo : Window
        {
            public AddImageToRtbDemo()
            {
                InitializeComponent();
                btn.Click += delegate
                {
                    Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
                    dlg.Filter = "Image Files(*.*) | *.*";
                    if (dlg.ShowDialog() == true)
                    {
                        Image image = new Image();
                        image.Loaded += delegate
                        {
                            AdornerLayer al = AdornerLayer.GetAdornerLayer(image);
                            if (al != null)
                            {
                                al.Add(new ResizingAdorner(image));
                            }
                        };
                        image.Source = new BitmapImage(new Uri(dlg.FileName, UriKind.Absolute)) { CacheOption = BitmapCacheOption.OnLoad };
                        BlockUIContainer container = new BlockUIContainer(image);
                        rtb.Document.Blocks.Add(container);
                    }
                };
            }
        }
    }
    


    You can find the ResizingAdorner implementation in the following link:
    http://msdn2.microsoft.com/en-us/library/ms771714.aspx

    Hope this helps

    Thursday, January 10, 2008 1:56 AM
  • you could use textrange.text = string;;

     

    where textrange = new TextRange(notes.Document.ContentStart, notes.Document.ContentEnd)'

     

    You could display the same plain text in the message box too.

     

     

    Tuesday, January 8, 2008 5:07 AM
    Moderator
  •  

    Just want to add that it's better to use InlineUIContainer instead of BlockUIContainer something like this:

     

    rtb.BeginChange();

    TextPointer tp = rtb.CaretPosition.GetPositionAtOffset(0, LogicalDirection.Forward);

    InlineUIContainer imageContainer = new InlineUIContainer(image, tp);

    rtb.CaretPosition = imageContainer.ElementEnd;

    rtb.EndChange();

    rtb.Focus();

     

    Add since you want to save images with FlowDocument you can use XamlReader\XamlWriter to save FlowDocument to db or elsewhere, something like this:

     

    public FlowDocument Convert(string note)

    {

    if (string.IsNullOrEmpty(note)) return null;

    try

    {

    using (XmlReader reader = XmlReader.Create(new StringReader(note)))

    {

    return XamlReader.Load(reader) as FlowDocument;

    }

    }

    catch (Exception) { }

    return null;

    }

    public string ConvertBack(FlowDocument doc)

    {

    if (doc == null) return string.Empty;

    try

    {

    using (TextWriter writer = new StringWriter())

    {

    XamlWriter.Save(doc, writer);

    return writer.ToString();

    }

    }

    catch (Exception) { }

    return string.Empty;

    }

     

     

    Thursday, January 10, 2008 2:06 AM
  • System.Windows.Controls.Image image = new System.Windows.Controls.Image Image();

     

    i failed to run for the above code..

    Thursday, January 10, 2008 5:07 AM
  •  

    OK how about:

    System.Windows.Controls.Image image = new System.Windows.Controls.Image();

     

    not:

    ... new System.Windows.Controls.Image Image();

    Thursday, January 10, 2008 5:15 AM

All replies

  • Hi!

    Your problem is thath the RichTextBox.Document property has the type FlowDocument instead of String. A String is not much more than a character array, but the FlowDocument stores "hosts and formats flow content with advanced document features, such as pagination and columns". The easiest way to get your app work is to add the string as the new paragraph, but I think you may want to do something more complex, otherwise you wouldn't use RichTextBox Smile

     

    Code Block

    contact_notes.Document = new FlowDocument(new Paragraph(new Run(row["notes"].ToString())));

     

     

    I hope I helped.

    Szász Bence

    Sunday, January 6, 2008 1:09 PM
  • thanks for the reply

     

    i followed your code .. contact_notes.Document = new FlowDocument(new Paragraph(new Run(row["notes"].ToString())));

     

    but in my richtextbox it show this

     

    System.Windows.Documents.FlowDocument

    Tuesday, January 8, 2008 12:32 AM
  • This works pretty well for me:
    String msg = "Windows Presentation Foundation";
    rtb.Document = new FlowDocument(new Paragraph(new Run(msg)));

    Or alternatively, you can do:

    String msg = "Windows Presentation Foundation";
    rtb.Document.Blocks.Add(new Paragraph(new Run(msg)));

    Hope this helps

    Tuesday, January 8, 2008 1:53 AM
  • string rtb = row["notes"].ToString();

    MessageBox.Show(rtb);  // got data shown

     

    contact_notes.Document = new FlowDocument(new Paragraph(new Run(rtb)));

     

    MessageBox.Show(contact_notes.Document);

     

    the messagebox shows

    (System.Windows.Documents.FlowDocument)  instead of any data

     

    i had declared using system.windows.documents..

    Tuesday, January 8, 2008 2:34 AM
  • What are you saving in your row dictionary (row["notes"])? 

     

    Looks like it's FlowDocument so use just contact_notes.Document = row["notes"]; without ToString().

    If it's xaml representation of FlowDocument then you can use:

    System.Windows.Markup.XamlReader.Load(System.Xml.XmlReader.Create(new System.IO.StringReader(row["notes"].ToString()))) as FlowDocument;

     

    Tuesday, January 8, 2008 2:45 AM
  •  

    > MessageBox.Show(contact_notes.Document);

     

    You can't display content of FlowDocument in MessageBox, use RichTextBox or

    FlowDocumentPageViewer; FlowDocumentReader;FlowDocumentScrollViewer

    Tuesday, January 8, 2008 2:58 AM
  • MessageBox is just a simply wrapper around Win32 dialog box, it cannot directly display WPF content, you can use the Window class instead, because Window can also support modal dialog behaviour as following snippet shows:
    Window wnd = new Window();
    wnd.Content = new FlowDocument(new Paragraph(new Run("Windows Presentation Foundation")));
    wnd.ShowDialog();

    Hope this helps

    Tuesday, January 8, 2008 4:38 AM
  • you could use textrange.text = string;;

     

    where textrange = new TextRange(notes.Document.ContentStart, notes.Document.ContentEnd)'

     

    You could display the same plain text in the message box too.

     

     

    Tuesday, January 8, 2008 5:07 AM
    Moderator
  •  

    thanks everyone.. one more problem.. is there anyway that i can upload a picture into my richtextbox ?? .. assume that my richtextbox is for people to write diary..

    i need to allow them to upload a picture inside.. and allow them to on the spot drag the picture border to resize the picture itself ..

    Thursday, January 10, 2008 12:37 AM
  • Here is an example of how to add image to the RichTextBox:

    Code Block
    <Window x:Class="MiscellaneousAnswers.AddImageToRtbDemo"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="AddImageToRtbDemo" Height="300" Width="300">
      <DockPanel>
        <Button DockPanel.Dock="Top" Width="120" Height="30" Name="btn" Content="Insert Image"/>
        <RichTextBox Name="rtb"/>
      </DockPanel>
    </Window>
    namespace MiscellaneousAnswers
    {
        public partial class AddImageToRtbDemo : Window
        {
            public AddImageToRtbDemo()
            {
                InitializeComponent();
                btn.Click += delegate
                {
                    Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
                    dlg.Filter = "Image Files(*.*) | *.*";
                    if (dlg.ShowDialog() == true)
                    {
                        Image image = new Image();
                        image.Loaded += delegate
                        {
                            AdornerLayer al = AdornerLayer.GetAdornerLayer(image);
                            if (al != null)
                            {
                                al.Add(new ResizingAdorner(image));
                            }
                        };
                        image.Source = new BitmapImage(new Uri(dlg.FileName, UriKind.Absolute)) { CacheOption = BitmapCacheOption.OnLoad };
                        BlockUIContainer container = new BlockUIContainer(image);
                        rtb.Document.Blocks.Add(container);
                    }
                };
            }
        }
    }
    


    You can find the ResizingAdorner implementation in the following link:
    http://msdn2.microsoft.com/en-us/library/ms771714.aspx

    Hope this helps

    Thursday, January 10, 2008 1:56 AM
  •  

    Just want to add that it's better to use InlineUIContainer instead of BlockUIContainer something like this:

     

    rtb.BeginChange();

    TextPointer tp = rtb.CaretPosition.GetPositionAtOffset(0, LogicalDirection.Forward);

    InlineUIContainer imageContainer = new InlineUIContainer(image, tp);

    rtb.CaretPosition = imageContainer.ElementEnd;

    rtb.EndChange();

    rtb.Focus();

     

    Add since you want to save images with FlowDocument you can use XamlReader\XamlWriter to save FlowDocument to db or elsewhere, something like this:

     

    public FlowDocument Convert(string note)

    {

    if (string.IsNullOrEmpty(note)) return null;

    try

    {

    using (XmlReader reader = XmlReader.Create(new StringReader(note)))

    {

    return XamlReader.Load(reader) as FlowDocument;

    }

    }

    catch (Exception) { }

    return null;

    }

    public string ConvertBack(FlowDocument doc)

    {

    if (doc == null) return string.Empty;

    try

    {

    using (TextWriter writer = new StringWriter())

    {

    XamlWriter.Save(doc, writer);

    return writer.ToString();

    }

    }

    catch (Exception) { }

    return string.Empty;

    }

     

     

    Thursday, January 10, 2008 2:06 AM
  • Code Block

    LesterLobo - MSFT

    Moderator


    Posts 1,340
    Re: richtextbox problems
    Was this post helpful ?
    Mark as correct answer

    you could use textrange.text = string;;

     

    where textrange = new TextRange(notes.Document.ContentStart, notes.Document.ContentEnd)'

     

    You could display the same plain text in the message box too.

     

    i tried your code.. but i think i change the error below of your code..

    textrange.text = string;;

     

     

     

    sting textrange;

    where textrange = new TextRange(notes.Document.ContentStart, notes.Document.ContentEnd)'

     

    but it said cannot assign into string.....

     

    i want to save to database as below

    Code Block

    cmd.CommandText = "insert into diary(title,Notes)" +

    "values('" + diary_title.Text + "','" + textrange+ "')";

     

     

     

     

     

    Thursday, January 10, 2008 2:12 AM
  •  

    you can't assign TextRange to string type.

     

    You can use like this:

     

    TextRange textRange = new TextRange(notes.Document.ContentStart, notes.Document.ContentEnd);

    string text = textRange.Text;

     

    But you won't be able to same Images like this. If you want to save Images see my reply above.

    Thursday, January 10, 2008 2:24 AM
  • hi .. when i follow your the code here.. this show the error below

    image is ambiguous reference between system.windows.controls.image and system.drawing.image

     

    i tried put this..

    System.Drawing.Image image = new System.Drawing.Image Image();

    worst still..


    Code Block

    if (dlg.ShowDialog() == true)
                    {
                       
    Image image = new Image();
                        image.Loaded +=
    delegate
                       
    {
                           
    AdornerLayer al = AdornerLayer.GetAdornerLayer(image);
                           
    if (al != null)
                            {
                                al.Add(
    new ResizingAdorner(image));
                            }
                        };

     

     

    Thursday, January 10, 2008 3:32 AM
  •  

    it's system.windows.controls.image
    Thursday, January 10, 2008 4:02 AM
  • System.Windows.Controls.Image image = new System.Windows.Controls.Image Image();

     

    i failed to run for the above code..

    Thursday, January 10, 2008 5:07 AM
  •  

    OK how about:

    System.Windows.Controls.Image image = new System.Windows.Controls.Image();

     

    not:

    ... new System.Windows.Controls.Image Image();

    Thursday, January 10, 2008 5:15 AM
  • great for the above..  but problems again ..huhh. am i missiong any refrence??

     

    Error 102 The type or namespace name 'ResizingAdorner' could not be found (are you missing a using directive or an assembly reference?)

    Error 103 The best overloaded method match for 'System.Windows.Documents.AdornerLayer.Add(System.Windows.Documents.Adorner)' has some invalid arguments .


    Error 104 Argument '1': cannot convert from 'ResizingAdorner' to 'System.Windows.Documents.Adorner' 


    Error 105 Method name expected 


    Error 106 The name 'CacheOption' does not exist in the current context 

    Thursday, January 10, 2008 5:22 AM
  • no it's ms sample here's the class:

     

    public class ResizingAdorner : Adorner

    {

    // Resizing adorner uses Thumbs for visual elements.

    // The Thumbs have built-in mouse input handling.

    Thumb topLeft, topRight, bottomLeft, bottomRight;

    // To store and manage the adorner's visual children.

    VisualCollection visualChildren;

    // Initialize the ResizingAdorner.

    public ResizingAdorner(UIElement adornedElement)

    : base(adornedElement)

    {

    visualChildren = new VisualCollection(this);

    // Call a helper method to initialize the Thumbs

    // with a customized cursors.

    BuildAdornerCorner(ref topLeft, Cursors.SizeNWSE);

    BuildAdornerCorner(ref topRight, Cursors.SizeNESW);

    BuildAdornerCorner(ref bottomLeft, Cursors.SizeNESW);

    BuildAdornerCorner(ref bottomRight, Cursors.SizeNWSE);

    // Add handlers for resizing.

    bottomLeft.DragDelta += new DragDeltaEventHandler(HandleBottomLeft);

    bottomRight.DragDelta += new DragDeltaEventHandler(HandleBottomRight);

    topLeft.DragDelta += new DragDeltaEventHandler(HandleTopLeft);

    topRight.DragDelta += new DragDeltaEventHandler(HandleTopRight);

    }

    // Handler for resizing from the bottom-right.

    void HandleBottomRight(object sender, DragDeltaEventArgs args)

    {

    FrameworkElement adornedElement = this.AdornedElement as FrameworkElement;

    Thumb hitThumb = sender as Thumb;

    if (adornedElement == null || hitThumb == null) return;

    FrameworkElement parentElement = adornedElement.Parent as FrameworkElement;

    // Ensure that the Width and Height are properly initialized after the resize.

    EnforceSize(adornedElement);

    // Change the size by the amount the user drags the mouse, as long as it's larger

    // than the width or height of an adorner, respectively.

    adornedElement.Width = Math.Max(adornedElement.Width + args.HorizontalChange, hitThumb.DesiredSize.Width);

    adornedElement.Height = Math.Max(args.VerticalChange + adornedElement.Height, hitThumb.DesiredSize.Height);

    }

    // Handler for resizing from the bottom-left.

    void HandleBottomLeft(object sender, DragDeltaEventArgs args)

    {

    FrameworkElement adornedElement = AdornedElement as FrameworkElement;

    Thumb hitThumb = sender as Thumb;

    if (adornedElement == null || hitThumb == null) return;

    // Ensure that the Width and Height are properly initialized after the resize.

    EnforceSize(adornedElement);

    // Change the size by the amount the user drags the mouse, as long as it's larger

    // than the width or height of an adorner, respectively.

    adornedElement.Width = Math.Max(adornedElement.Width - args.HorizontalChange, hitThumb.DesiredSize.Width);

    adornedElement.Height = Math.Max(args.VerticalChange + adornedElement.Height, hitThumb.DesiredSize.Height);

    }

    // Handler for resizing from the top-right.

    void HandleTopRight(object sender, DragDeltaEventArgs args)

    {

    FrameworkElement adornedElement = this.AdornedElement as FrameworkElement;

    Thumb hitThumb = sender as Thumb;

    if (adornedElement == null || hitThumb == null) return;

    FrameworkElement parentElement = adornedElement.Parent as FrameworkElement;

    // Ensure that the Width and Height are properly initialized after the resize.

    EnforceSize(adornedElement);

    // Change the size by the amount the user drags the mouse, as long as it's larger

    // than the width or height of an adorner, respectively.

    adornedElement.Width = Math.Max(adornedElement.Width + args.HorizontalChange, hitThumb.DesiredSize.Width);

    adornedElement.Height = Math.Max(adornedElement.Height - args.VerticalChange, hitThumb.DesiredSize.Height);

    }

    // Handler for resizing from the top-left.

    void HandleTopLeft(object sender, DragDeltaEventArgs args)

    {

    FrameworkElement adornedElement = AdornedElement as FrameworkElement;

    Thumb hitThumb = sender as Thumb;

    if (adornedElement == null || hitThumb == null) return;

    // Ensure that the Width and Height are properly initialized after the resize.

    EnforceSize(adornedElement);

    // Change the size by the amount the user drags the mouse, as long as it's larger

    // than the width or height of an adorner, respectively.

    adornedElement.Width = Math.Max(adornedElement.Width - args.HorizontalChange, hitThumb.DesiredSize.Width);

    adornedElement.Height = Math.Max(adornedElement.Height - args.VerticalChange, hitThumb.DesiredSize.Height);

    }

    // Arrange the Adorners.

    protected override Size ArrangeOverride(Size finalSize)

    {

    // desiredWidth and desiredHeight are the width and height of the element that's being adorned.

    // These will be used to place the ResizingAdorner at the corners of the adorned element.

    double desiredWidth = AdornedElement.DesiredSize.Width;

    double desiredHeight = AdornedElement.DesiredSize.Height;

    // adornerWidth & adornerHeight are used for placement as well.

    double adornerWidth = this.DesiredSize.Width;

    double adornerHeight = this.DesiredSize.Height;

    topLeft.Arrange(new Rect(-adornerWidth / 2, -adornerHeight / 2, adornerWidth, adornerHeight));

    topRight.Arrange(new Rect(desiredWidth - adornerWidth / 2, -adornerHeight / 2, adornerWidth, adornerHeight));

    bottomLeft.Arrange(new Rect(-adornerWidth / 2, desiredHeight - adornerHeight / 2, adornerWidth, adornerHeight));

    bottomRight.Arrange(new Rect(desiredWidth - adornerWidth / 2, desiredHeight - adornerHeight / 2, adornerWidth, adornerHeight));

    // Return the final size.

    return finalSize;

    }

    // Helper method to instantiate the corner Thumbs, set the Cursor property,

    // set some appearance properties, and add the elements to the visual tree.

    void BuildAdornerCorner(ref Thumb cornerThumb, Cursor customizedCursor)

    {

    if (cornerThumb != null) return;

    cornerThumb = new Thumb();

    // Set some arbitrary visual characteristics.

    cornerThumb.Cursor = customizedCursor;

    cornerThumb.Height = cornerThumb.Width = 10;

    cornerThumb.Opacity = 0.40;

    cornerThumb.Background = new SolidColorBrush(Colors.MediumBlue);

    visualChildren.Add(cornerThumb);

    }

    // This method ensures that the Widths and Heights are initialized. Sizing to content produces

    // Width and Height values of Double.NaN. Because this Adorner explicitly resizes, the Width and Height

    // need to be set first. It also sets the maximum size of the adorned element.

    void EnforceSize(FrameworkElement adornedElement)

    {

    if (adornedElement.Width.Equals(Double.NaN))

    adornedElement.Width = adornedElement.DesiredSize.Width;

    if (adornedElement.Height.Equals(Double.NaN))

    adornedElement.Height = adornedElement.DesiredSize.Height;

    FrameworkElement parent = adornedElement.Parent as FrameworkElement;

    if (parent != null)

    {

    adornedElement.MaxHeight = parent.ActualHeight;

    adornedElement.MaxWidth = parent.ActualWidth;

    }

    }

    // Override the VisualChildrenCount and GetVisualChild properties to interface with

    // the adorner's visual collection.

    protected override int VisualChildrenCount { get { return visualChildren.Count; } }

    protected override Visual GetVisualChild(int index) { return visualChildren[index]; }

    }

     

    Thursday, January 10, 2008 5:32 AM
  •  

    This is of great help for me. But I need it in  VB.NET. I tried to convert it using some resources available but getting some problems. Does anyone has the VB.NET version of the same code?
    Monday, March 31, 2008 2:10 PM