WPF Multitab编辑器保存功能

时间:2014-05-05 23:57:49

标签: c# wpf save richtextbox

我正在WPF中实现一个文本编辑器,我已经达到了一个阶段,我可以在应用程序的选项卡中打开多个文件。代码如下。现在我需要为文本编辑器实现保存功能。为此,我需要知道哪个特定的Tab对我来说是单独保存该文件。我该如何使用此功能?我的标签也没有关闭按钮(' X')。如何在WPF中实现关闭按钮功能?任何帮助表示赞赏。

public partial class MainWindow : Window
            {
                public MainWindow()
                {
                    InitializeComponent();  
                } 

private void Open_Click(object sender, RoutedEventArgs e)
        {    
 Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

                dlg.DefaultExt = ".txt";
                dlg.Filter = "Text Files(*.txt)|*.txt";

                Nullable<bool> result = dlg.ShowDialog();
                mode openfile = mode.openFile;

                if (result.HasValue == true)
                {
                    if (File.Exists(dlg.FileName))
                        AddTabitem(dlg.FileName, openfile);
                    else
                        MessageBox.Show("NoSuch file exsists", "OpenError");

                }
            }

            private void AddTabitem(string filePath, mode fileMode) 
            {
                    TextRange range;
                    FileStream fStream;

                    if (fileMode == mode.openFile)
                    {
                        if (File.Exists(filePath))
                        {
                            RichTextBox mcRTB = new RichTextBox();
                            rtbList.Add(mcRTB);
                            TabItem tab = new TabItem();

                            try
                            {
                                range = new TextRange(mcRTB.Document.ContentStart, mcRTB.Document.ContentEnd);
                                fStream = new FileStream(filePath, FileMode.OpenOrCreate);
                                range.Load(fStream, DataFormats.Text);
                                fStream.Close();
                            }
                            catch(Exception)
                            {
                                MessageBox.Show("Unable to open specified file.", "Open File error", MessageBoxButton.OK);
                            }

                            tab.Header = ExtractFileName(filePath);
                            tab.Content = mcRTB;

                            EditorTabcontrol.Items.Insert(EditorTabcontrol.Items.Count, tab);
                            EditorTabcontrol.SelectedIndex = EditorTabcontrol.Items.Count - 1;    
                        }
                    }
        }

<ScrollViewer  VerticalScrollBarVisibility="Auto">
                <TabControl Width="648" Name="EditorTabcontrol" AllowDrop="True"/>
            </ScrollViewer>

1 个答案:

答案 0 :(得分:1)

EditorTabcontrol(类型为TabControl)具有SelectedItem属性,您可以使用它来标识当前处于活动状态的编辑器。从那里你可以得到它的内容。

要添加关闭(x)按钮,您需要将TabItem的Header属性设置为StackPanel(水平的)而不是简单的字符串,并添加字符串(文件名)和按钮(文本X或适当的图像)到Stackpanel。然后处理按钮的Click事件。

相关问题