You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF中FlowDocumentScrollViewer绑定后无法显示文本问题求助

问题原因及修复方案

核心问题

  • RunSM方法语法错误:方法定义缺少括号,正确写法应为private void RunSM()。
  • 未将段落添加到FlowDocument:创建Paragraph后,没有把它加入FlowDocument的内容集合里。
  • 未更新绑定的FlowDocument属性:界面的FlowDocumentScrollViewer绑定的是FlowDocument属性,但你在方法里新建了FlowDocumentScrollViewer实例,完全没用到绑定的数据源,界面自然不会更新。
  • 冗余的FlowDocumentScrollViewer属性:MVVM模式下,ViewModel不需要持有UI控件实例,应通过数据绑定更新内容,而非直接操作控件。

修复后的ViewModel代码

private ICommand m_SomeButtonCommand;
public ICommand SomeButton => m_SomeButtonCommand ?? (m_SomeButtonCommand = new RelayCommand(RunSM, true));

private void RunSM() // 修复方法括号
{
    FlowDocument flowDocument = new FlowDocument();
    Paragraph paragraph = new Paragraph(new Run("some new Text"));

    paragraph.Background = Brushes.White;
    paragraph.Foreground = Brushes.Black;
    paragraph.FontSize = 14;

    flowDocument.Blocks.Add(paragraph); // 将段落添加到文档内容中
    FlowDocument = flowDocument; // 更新绑定属性,触发界面刷新
}

// 移除不必要的FlowDocumentScrollViewer相关属性
private FlowDocument m_flowDocument;
public FlowDocument FlowDocument
{
    get
    {
        return m_flowDocument;
    }

    set
    {
        if (m_flowDocument == value)
            return;

        m_flowDocument = value;
        OnPropertyChanged();
    }
}

说明

  • 原XAML代码无需修改,它已经正确绑定了FlowDocument属性。
  • 遵循MVVM原则:ViewModel只处理数据与业务逻辑,通过更新绑定的数据源驱动界面变化,不直接操作UI控件。
  • 修复后点击按钮,FlowDocument属性会被更新,界面的FlowDocumentScrollViewer会自动加载新的文档内容。

内容的提问来源于stack exchange,提问作者4est

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 05:25:51