RichTextBox切换视图模型时丢失内容

时间:2019-05-25 23:01:46

标签: wpf richtextbox

我已经设置了一个类似wpf窗口的选项卡以在视图模型之间切换。主窗口看起来像这样。

    <Window.Resources>
    <DataTemplate DataType="{x:Type skyTelescope:SkyTelescopeVM}">
        <skyTelescope:SkyTelescopeV />
    </DataTemplate>
    <DataTemplate DataType="{x:Type charting:ChartingVM}">
        <charting:ChartingV />
    </DataTemplate>
    <DataTemplate DataType="{x:Type focuser:FocuserVM}">
          <focuser:FocuserView />
    </DataTemplate>
    <DataTemplate DataType="{x:Type notes:NotesVM}">
        <notes:NotesV />
    </DataTemplate>
    <DataTemplate DataType="{x:Type settings:SettingsVM}">
        <settings:SettingsV />
    </DataTemplate>
</Window.Resources>
<Grid Height="510" Width="800">
    <Grid.RowDefinitions>
        <RowDefinition Height="30"/>
        <RowDefinition Height="40"/>
        <RowDefinition Height="440"/>
    </Grid.RowDefinitions>
    <mcontrol:WindowTitleBar Grid.Row="0" />
    <mcontrol:TabBar Grid.Row="1" />
    <Grid Grid.Row="2">
        <ContentControl Content="{Binding CurrentPageViewModel}" />
    </Grid>
</Grid>

NotesV视图是一个UserControl并具有RichTextBox。我使用了后面的代码来设置所有必要的编辑按钮。我的问题是,当我切换到另一个视图模型然后再返回时,我会丢失所有RTB内容。我不确定为什么会这样……似乎正在失去状态或上下文。任何帮助表示赞赏。

更新:每次看起来都像它的InitializeComponent,所以用下面的代码将其保存到静态类中似乎可行,但效率不高。

SelectionChanged事件将其保存。...

   using (var ms = new MemoryStream())
        {
            var range2 = new TextRange(rtbEditor.Document.ContentStart, rtbEditor.Document.ContentEnd);
            range2.Save(ms, DataFormats.Rtf);
            ms.Seek(0, SeekOrigin.Begin);
            using (var sr = new StreamReader(ms))
            {
                SkyServer.Notes = sr.ReadToEnd();
            }
        }

构造函数代码。...

   if (!string.IsNullOrEmpty(SkyServer.Notes))
        {
            Stream SM = new MemoryStream(Encoding.UTF8.GetBytes(SkyServer.Notes));
            var range = new TextRange(rtbEditor?.Document.ContentStart, rtbEditor?.Document.ContentEnd);
            range.Load(SM, DataFormats.Rtf);
            SM.Close();
        }

0 个答案:

没有答案
相关问题