c# - 在可绑定(bind)的 RichTexBox 中加载 rtf mvvm wpf

标签 c# wpf mvvm binding richtextbox

我是 mvvm 的新手,我想使用 mvvm 在 RichTextBox 中加载一个 rtf 文件,但文本似乎没有显示在我的 richtextbox 中。看起来 RichTextBox 在尝试将命令放置在 ViewModel 中时处理起来非常复杂。我不确定哪里出错了。

View 模型

 FlowDocument _script;
 public FlowDocument Script 
    {
        get { return _script; }
        set { _script = value; RaisePropertyChanged("Script"); }
    }
.
.
.
 private void LoadScript()
    {
        openFile.InitialDirectory = "C:\\";

        if (openFile.ShowDialog() == true)
        {
            string originalfilename = System.IO.Path.GetFullPath(openFile.FileName);

            if (openFile.CheckFileExists)
            {
                Script = new FlowDocument();
                TextRange range = new TextRange(Script.ContentStart, Script.ContentEnd);
                FileStream fStream = new FileStream(originalfilename, System.IO.FileMode.OpenOrCreate);
                range.Load(fStream, DataFormats.Rtf);
                fStream.Close();
            }  
         }
    }

View

DataContext="{Binding ScriptBreakdownViewModel, Source={StaticResource Locator}}">

<Grid>
    <RichTextBox
        Local:RichTextBoxHelper.DocumentRtf="{Binding Script}"
        x:Name="rtfMain"
        HorizontalAlignment="Left"
        Width="673"
        VerticalScrollBarVisibility="Visible"
        Margin="0,59,0,10.4"
        />

RichTextBoxHelper

public class RichTextBoxHelper : DependencyObject
{
    public static string GetDocumentRtf(DependencyObject obj)
    {
        return (string)obj.GetValue(DocumentRtfProperty);
    }
    public static void SetDocumentRtf(DependencyObject obj, string value)
    {
        obj.SetValue(DocumentRtfProperty, value);
    }
    public static readonly DependencyProperty DocumentRtfProperty =
      DependencyProperty.RegisterAttached(
        "DocumentRtf",
        typeof(string),
        typeof(RichTextBoxHelper),
        new FrameworkPropertyMetadata
        {
            BindsTwoWayByDefault = true,
            PropertyChangedCallback = (obj, e) =>
            {
                var richTextBox = (RichTextBox)obj;

               //  Parse the XAML to a document (or use XamlReader.Parse())
                var Rtf = GetDocumentRtf(richTextBox);
                var doc = new FlowDocument();
                var range = new TextRange(doc.ContentStart, doc.ContentEnd);

                range.Load(new MemoryStream(Encoding.UTF8.GetBytes(Rtf)),
                  DataFormats.Rtf);

               //  Set the document
                richTextBox.Document = doc;

               //  When the document changes update the source
                range.Changed += (obj2, e2) =>
                {
                    if (richTextBox.Document == doc)
                    {
                        MemoryStream buffer = new MemoryStream();
                        range.Save(buffer, DataFormats.Rtf);
                        SetDocumentRtf(richTextBox,
                          Encoding.UTF8.GetString(buffer.ToArray()));
                    }
                };
            }
        });
}

和模型

  FlowDocument _script;
  public FlowDocument Script   // the Name property
    {
        get { return _script; }
        set { _script = value; NotifyPropertyChanged("Script"); }
    }

最佳答案

我试图填补您上面示例代码中的空白,但您的依赖属性从未被触发。

相反,我通过稍微更改 XAML 来填充 RichTextBox:

    <Button Height="30" Width="70" VerticalAlignment="Top" Command="{Binding OpenFileCommand}" CommandParameter="{Binding ElementName=myRichTextBox}">Load</Button>
    <RichTextBox Name="myRichTextBox"
        HorizontalAlignment="Left"
        Width="673"
        VerticalScrollBarVisibility="Visible"
        Margin="0,59,0,10.4"></RichTextBox>

有一个按钮绑定(bind)到 OpenFileCommand,它是 ViewModel 的一个属性。它将 RichTextBox 作为参数传递给命令本身。我已将 LoadScript() 方法从 ViewModel 移至命令。

public class OpenFileCommand : ICommand
{
    private OpenFileDialog openFile = new OpenFileDialog();

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public void Execute(object parameter)
    {
        var rtf = parameter as RichTextBox;
        rtf.Document = LoadScript();
    }

    public event EventHandler CanExecuteChanged;

    private FlowDocument LoadScript()
    {
        openFile.InitialDirectory = "C:\\";

        if (openFile.ShowDialog() == true)
        {
            string originalfilename = System.IO.Path.GetFullPath(openFile.FileName);

            if (openFile.CheckFileExists)
            {
                var script = new FlowDocument();
                TextRange range = new TextRange(script.ContentStart, script.ContentEnd);
                FileStream fStream = new FileStream(originalfilename, System.IO.FileMode.OpenOrCreate);
                range.Load(fStream, DataFormats.Rtf);
                fStream.Close();
                return script;
            }
        }

        return null;
    }
}

关于c# - 在可绑定(bind)的 RichTexBox 中加载 rtf mvvm wpf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30821339/

相关文章:

c# - MVVM light Dispatcher 单元测试

c# - 控制台应用程序中的 System.Drawing.Color

c# - 如何检查 List < int[ ] > 是否包含与另一个 int[ ] 存储相同值的 int[] 元素?

c# - 如何将快捷方式(.lnk)包含到解决方案中?

c# - 在 UWP、MVVM 中实现周期性进程

c# - WPF - MVVM - 谁负责新的 DataProvider 连接?

c# - AES输出,它比输入小吗?

c# - AAS 模型暂停和恢复后,尝试打开 ADOMD.net 连接返回 307 响应

wpf - 处理冗长的异步任务并通知用户

wpf - CollectionViewSource : TreeView not updating, ViewModel 看起来不错