1

Вставляются вместо картинки символы

яШяаЃЉИ...

    ImageOpenDialog1();



    public void ImageOpenDialog1()
    {
        // Configure open file dialog box
        Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
        dlg.FileName = ""; // Default file name
        dlg.DefaultExt = ".jpg"; // Default file extension
        dlg.Filter = "Text documents |*.jpg"; // Filter files by extension

        // Show open file dialog box
        Nullable<bool> result = dlg.ShowDialog();

        // Process open file dialog box results
        if (result == true)
        {
            // Open document
            string filename = dlg.FileName;

            //
            textEditor.Load(dlg.FileName);

        }
    }

Обновлено:

public class TextEditor : RichTextBox /*Control*/, ITextEditorComponent, IServiceProvider, IWeakEventListener 
    {
        #region Constructors
        static TextEditor()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(TextEditor),
                                                     new FrameworkPropertyMetadata(typeof(TextEditor)));
            FocusableProperty.OverrideMetadata(typeof(TextEditor),
                                               new FrameworkPropertyMetadata(Boxes.True));
        }
...
        /// <summary>
        /// Loads the text from the stream, auto-detecting the encoding.
        /// </summary>
        /// <remarks>
        /// This method sets <see cref="IsModified"/> to false.
        /// </remarks>
        public void Load(Stream stream)
        {
            using (StreamReader reader = FileReader.OpenStream(stream, this.Encoding ?? Encoding.UTF8)) {
                this.Text = reader.ReadToEnd();
                SetCurrentValue(EncodingProperty, reader.CurrentEncoding); // assign encoding after ReadToEnd() so that the StreamReader can autodetect the encoding
            }
            SetCurrentValue(IsModifiedProperty, Boxes.False);
        }

        /// <summary>
        /// Loads the text from the stream, auto-detecting the encoding.
        /// </summary>
        public void Load(string fileName)
        {
            if (fileName == null)
                throw new ArgumentNullException("fileName");
            using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) {
                Load(fs);
            }
        }

Добавлено

public class TextEditor : RichTextBox /*Control*/, ITextEditorComponent, IServiceProvider, IWeakEventListener 
    {

....
        /// <summary>
        /// Gets/Sets the document displayed by the text editor.
        /// This is a dependency property.
        /// </summary>
        public TextDocument Document {
            get { return (TextDocument)GetValue(DocumentProperty); }
            set { SetValue(DocumentProperty, value); }
        }

TextDocument

namespace ICSharpCode.AvalonEdit.Document
{
    /// <summary>
    /// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events.
    /// </summary>
    /// <remarks>
    /// <b>Thread safety:</b>
    /// <inheritdoc cref="VerifyAccess"/>
    /// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para>
    /// </remarks>
    public sealed class TextDocument : IDocument, INotifyPropertyChanged
    {

    ...

    #region Fields + Constructor
    readonly Rope<char> rope;
    readonly DocumentLineTree lineTree;
    readonly LineManager lineManager;
    readonly TextAnchorTree anchorTree;
    readonly TextSourceVersionProvider versionProvider = new TextSourceVersionProvider();

    /// <summary>
    /// Create an empty text document.
    /// </summary>
    public TextDocument()
        : this(string.Empty)
    {
    }

    /// <summary>
    /// Create a new text document with the specified initial text.
    /// </summary>
    public TextDocument(IEnumerable<char> initialText)
    {
        if (initialText == null)
            throw new ArgumentNullException("initialText");
        rope = new Rope<char>(initialText);
        lineTree = new DocumentLineTree(this);
        lineManager = new LineManager(lineTree, this);
        lineTrackers.CollectionChanged += delegate {
            lineManager.UpdateListOfLineTrackers();
        };

        anchorTree = new TextAnchorTree(this);
        undoStack = new UndoStack();
        FireChangeEvents();
    }

    /// <summary>
    /// Create a new text document with the specified initial text.
    /// </summary>
    public TextDocument(ITextSource initialText)
        : this(GetTextFromTextSource(initialText))
    {
    }

    // gets the text from a text source, directly retrieving the underlying rope where possible
    static IEnumerable<char> GetTextFromTextSource(ITextSource textSource)
    {
        if (textSource == null)
            throw new ArgumentNullException("textSource");

        #if NREFACTORY
        if (textSource is ReadOnlyDocument)
            textSource = textSource.CreateSnapshot(); // retrieve underlying text source, which might be a RopeTextSource
        #endif

        RopeTextSource rts = textSource as RopeTextSource;
        if (rts != null)
            return rts.GetRope();

        TextDocument doc = textSource as TextDocument;
        if (doc != null)
            return doc.rope;

        return textSource.Text;
    }
    #endregion

IDocument

namespace ICSharpCode.AvalonEdit.Document
{
    #if !NREFACTORY
    /// <summary>
    /// A document representing a source code file for refactoring.
    /// Line and column counting starts at 1.
    /// Offset counting starts at 0.
    /// </summary>
    public interface IDocument : ITextSource, IServiceProvider
    {
        #if NREFACTORY
        /// <summary>
        /// Creates an immutable snapshot of this document.
        /// </summary>
        IDocument CreateDocumentSnapshot();
        #endif

        /// <summary>
        /// Gets/Sets the text of the whole document..
        /// </summary>
        new string Text { get; set; } // hides ITextSource.Text to add the setter

        /// <summary>
        /// This event is called directly before a change is applied to the document.
        /// </summary>
        /// <remarks>
        /// It is invalid to modify the document within this event handler.
        /// Aborting the change (by throwing an exception) is likely to cause corruption of data structures
        /// that listen to the Changing and Changed events.
        /// </remarks>
        event EventHandler<TextChangeEventArgs> TextChanging;

        /// <summary>
        /// This event is called directly after a change is applied to the document.
        /// </summary>
        /// <remarks>
        /// It is invalid to modify the document within this event handler.
        /// Aborting the event handler (by throwing an exception) is likely to cause corruption of data structures
        /// that listen to the Changing and Changed events.
        /// </remarks>
        event EventHandler<TextChangeEventArgs> TextChanged;

        /// <summary>
        /// This event is called after a group of changes is completed.
        /// </summary>
        /// <seealso cref="EndUndoableAction"/>
        event EventHandler ChangeCompleted;

        /// <summary>
        /// Gets the number of lines in the document.
        /// </summary>
        int LineCount { get; }

        /// <summary>
        /// Gets the document line with the specified number.
        /// </summary>
        /// <param name="lineNumber">The number of the line to retrieve. The first line has number 1.</param>
        IDocumentLine GetLineByNumber(int lineNumber);

        /// <summary>
        /// Gets the document line that contains the specified offset.
        /// </summary>
        IDocumentLine GetLineByOffset(int offset);

        /// <summary>
        /// Gets the offset from a text location.
        /// </summary>
        /// <seealso cref="GetLocation"/>
        int GetOffset(int line, int column);

        /// <summary>
        /// Gets the offset from a text location.
        /// </summary>
        /// <seealso cref="GetLocation"/>
        int GetOffset(TextLocation location);

        /// <summary>
        /// Gets the location from an offset.
        /// </summary>
        /// <seealso cref="GetOffset(TextLocation)"/>
        TextLocation GetLocation(int offset);

        /// <summary>
        /// Inserts text.
        /// </summary>
        /// <param name="offset">The offset at which the text is inserted.</param>
        /// <param name="text">The new text.</param>
        /// <remarks>
        /// Anchors positioned exactly at the insertion offset will move according to their movement type.
        /// For AnchorMovementType.Default, they will move behind the inserted text.
        /// The caret will also move behind the inserted text.
        /// </remarks>
        void Insert(int offset, string text);

        /// <summary>
        /// Inserts text.
        /// </summary>
        /// <param name="offset">The offset at which the text is inserted.</param>
        /// <param name="text">The new text.</param>
        /// <remarks>
        /// Anchors positioned exactly at the insertion offset will move according to their movement type.
        /// For AnchorMovementType.Default, they will move behind the inserted text.
        /// The caret will also move behind the inserted text.
        /// </remarks>
        void Insert(int offset, ITextSource text);

        /// <summary>
        /// Inserts text.
        /// </summary>
        /// <param name="offset">The offset at which the text is inserted.</param>
        /// <param name="text">The new text.</param>
        /// <param name="defaultAnchorMovementType">
        /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
        /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
        /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
        /// </param>
        void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType);

        /// <summary>
        /// Inserts text.
        /// </summary>
        /// <param name="offset">The offset at which the text is inserted.</param>
        /// <param name="text">The new text.</param>
        /// <param name="defaultAnchorMovementType">
        /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type.
        /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter.
        /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter.
        /// </param>
        void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType);

        /// <summary>
        /// Removes text.
        /// </summary>
        /// <param name="offset">Starting offset of the text to be removed.</param>
        /// <param name="length">Length of the text to be removed.</param>
        void Remove(int offset, int length);

        /// <summary>
        /// Replaces text.
        /// </summary>
        /// <param name="offset">The starting offset of the text to be replaced.</param>
        /// <param name="length">The length of the text to be replaced.</param>
        /// <param name="newText">The new text.</param>
        void Replace(int offset, int length, string newText);

        /// <summary>
        /// Replaces text.
        /// </summary>
        /// <param name="offset">The starting offset of the text to be replaced.</param>
        /// <param name="length">The length of the text to be replaced.</param>
        /// <param name="newText">The new text.</param>
        void Replace(int offset, int length, ITextSource newText);

        /// <summary>
        /// Make the document combine the following actions into a single
        /// action for undo purposes.
        /// </summary>
        void StartUndoableAction();

        /// <summary>
        /// Ends the undoable action started with <see cref="StartUndoableAction"/>.
        /// </summary>
        void EndUndoableAction();

        /// <summary>
        /// Creates an undo group. Dispose the returned value to close the undo group.
        /// </summary>
        /// <returns>An object that closes the undo group when Dispose() is called.</returns>
        IDisposable OpenUndoGroup();

        /// <summary>
        /// Creates a new <see cref="ITextAnchor"/> at the specified offset.
        /// </summary>
        /// <inheritdoc cref="ITextAnchor" select="remarks|example"/>
        ITextAnchor CreateAnchor(int offset);

        /// <summary>
        /// Gets the name of the file the document is stored in.
        /// Could also be a non-existent dummy file name or null if no name has been set.
        /// </summary>
        string FileName { get; }

        /// <summary>
        /// Fired when the file name of the document changes.
        /// </summary>
        event EventHandler FileNameChanged;
    }

    /// <summary>
    /// A line inside a <see cref="IDocument"/>.
    /// </summary>
    public interface IDocumentLine : ISegment
    {
        /// <summary>
        /// Gets the length of this line, including the line delimiter.
        /// </summary>
        int TotalLength { get; }

        /// <summary>
        /// Gets the length of the line terminator.
        /// Returns 1 or 2; or 0 at the end of the document.
        /// </summary>
        int DelimiterLength { get; }

        /// <summary>
        /// Gets the number of this line.
        /// The first line has the number 1.
        /// </summary>
        int LineNumber { get; }

        /// <summary>
        /// Gets the previous line. Returns null if this is the first line in the document.
        /// </summary>
        IDocumentLine PreviousLine { get; }

        /// <summary>
        /// Gets the next line. Returns null if this is the last line in the document.
        /// </summary>
        IDocumentLine NextLine { get; }

        /// <summary>
        /// Gets whether the line was deleted.
        /// </summary>
        bool IsDeleted { get; }
    }

    /// <summary>
    /// Describes a change of the document text.
    /// This class is thread-safe.
    /// </summary>
    [Serializable]
    public class TextChangeEventArgs : EventArgs
    {
        readonly int offset;
        readonly ITextSource removedText;
        readonly ITextSource insertedText;

        /// <summary>
        /// The offset at which the change occurs.
        /// </summary>
        public int Offset {
            get { return offset; }
        }

        /// <summary>
        /// The text that was removed.
        /// </summary>
        public ITextSource RemovedText {
            get { return removedText; }
        }

        /// <summary>
        /// The number of characters removed.
        /// </summary>
        public int RemovalLength {
            get { return removedText.TextLength; }
        }

        /// <summary>
        /// The text that was inserted.
        /// </summary>
        public ITextSource InsertedText {
            get { return insertedText; }
        }

        /// <summary>
        /// The number of characters inserted.
        /// </summary>
        public int InsertionLength {
            get { return insertedText.TextLength; }
        }

        /// <summary>
        /// Creates a new TextChangeEventArgs object.
        /// </summary>
        public TextChangeEventArgs(int offset, string removedText, string insertedText)
        {
            if (offset < 0)
                throw new ArgumentOutOfRangeException("offset", offset, "offset must not be negative");
            this.offset = offset;
            this.removedText = removedText != null ? new StringTextSource(removedText) : StringTextSource.Empty;
            this.insertedText = insertedText != null ? new StringTextSource(insertedText) : StringTextSource.Empty;
        }

        /// <summary>
        /// Creates a new TextChangeEventArgs object.
        /// </summary>
        public TextChangeEventArgs(int offset, ITextSource removedText, ITextSource insertedText)
        {
            if (offset < 0)
                throw new ArgumentOutOfRangeException("offset", offset, "offset must not be negative");
            this.offset = offset;
            this.removedText = removedText ?? StringTextSource.Empty;
            this.insertedText = insertedText ?? StringTextSource.Empty;
        }

        /// <summary>
        /// Gets the new offset where the specified offset moves after this document change.
        /// </summary>
        public virtual int GetNewOffset(int offset, AnchorMovementType movementType = AnchorMovementType.Default)
        {
            if (offset >= this.Offset && offset <= this.Offset + this.RemovalLength) {
                if (movementType == AnchorMovementType.BeforeInsertion)
                    return this.Offset;
                else
                    return this.Offset + this.InsertionLength;
            } else if (offset > this.Offset) {
                return offset + this.InsertionLength - this.RemovalLength;
            } else {
                return offset;
            }
        }

        /// <summary>
        /// Creates TextChangeEventArgs for the reverse change.
        /// </summary>
        public virtual TextChangeEventArgs Invert()
        {
            return new TextChangeEventArgs(offset, insertedText, removedText);
        }
    }
    #endif
}

1 ответ 1

1

Какого типа ваш textEditor? У RichTextBox я не нашёл метода Load.

У меня работает такой код:

var source = BitmapFrame.Create(new Uri(@"D:\test.png")); // <-- подставляете сюда путь
var image = new Image() { Source = source };              //     к картинке
var container = new InlineUIContainer(image, textEditor.Document.ContentStart);
11
  • TextEditor переопределён TextEditor : RichTextBox /*Control*/
    – code211218
    25 янв 2017 в 11:49
  • var container = new InlineUIContainer(image, textEditor.Document.ContentStart); >Ошибка CS1061 'TextDocument" не содержит определения для "ContentStart" и не удалось найти метод расширения "ContentStart", принимающий тип "TextDocument" в качестве первого аргумента (возможно, пропущена директива using или ссылка на сборку).
    – code211218
    25 янв 2017 в 11:50
  • 1
    @codename0082016: Ну, хм. Я не знаю, что делает ваш TextDocument. Попробуйте мой код со стандартным RichTextBox'ом, он должен по идее работать. Попробуйте ещё ((RichTextBox)textEditor).Document.ContentStart.
    – VladD
    25 янв 2017 в 17:13
  • 1
    @codename0082016: Вы, возможно, перелопатили RichTextBox в вашем классе настолько, что он теперь не вполне совместим со стандартным RichTextBox'ом.
    – VladD
    25 янв 2017 в 17:14
  • 1
    @codename0082016: Подождите, вы что-то делаете не так. FlowDocument должен быть подэлементом RichTextBox (ну или подэлементом FlowDocumentReader), а у вас наоборот почему-то.
    – VladD
    25 янв 2017 в 17:52

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.