xargs
xargs

Reputation: 3079

Save RichTextBox's content to file using MVVM

I have a problem with RichTextBox and I would like to save the content of the document in a text file. For that I use the next code:

XAML

<RichTextBox Grid.Row="0" x:Name="myRichTextBox" AcceptsTab="True" Margin="20">
    <FlowDocument>
        <Paragraph>
            <Run>Some Paragraph</Run>
        </Paragraph>
    </FlowDocument>
</RichTextBox>

Code

private void btnSaveToTxt_Click(object sender, RoutedEventArgs e)
{
    string fileName = @"D:\testRichTextBox1Text.txt";
    SaveToTextFile(fileName);

    MessageBox.Show("Text File Saved");
}

public void SaveToTextFile(string fileName)
{
    TextRange range;
    FileStream fileStream;

    range = new TextRange(myRichTextBox.Document.ContentStart,
                              myRichTextBox.Document.ContentEnd);

    fileStream = new FileStream(fileName, FileMode.Create);
    range.Save(fileStream, DataFormats.Text);

    fileStream.Close();
}

This code is Ok and it works, but how would I do this with MVVM. For this approach I need the RichTextBox's x:Name="myRichTextBox" property. I was thinking to bind a ICommand to invoke SaveToTextFile() method, but without the Name property from RichTextBox it wont work.

Is there a way to do this with MVVM ? Thanks!

Upvotes: 3

Views: 2959

Answers (1)

Jawahar
Jawahar

Reputation: 4885

The viewmodel don't need the Name property. To save the document it just need the FlowDocument object. So create a command for Save operation and pass the FlowDocument instance through CommandParameter.

public class ViewModel 
{
    string fileName = @"D:\testRichTextBox1Text.txt";

    private ICommand saveCommand;

    public ICommand SaveCommand
    {
        get
        {
            if (saveCommand == null)
            {
                saveCommand = new DelegateCommand(SaveToTextFile);
            }
            return saveCommand;
        }
    }

    public void SaveToTextFile(object document)
    {
        TextRange range;
        FileStream fileStream;

        range = new TextRange(((FlowDocument)document).ContentStart,
                              ((FlowDocument)document).ContentEnd);

        fileStream = new FileStream(fileName, FileMode.Create);
        range.Save(fileStream, DataFormats.Text);
        fileStream.Close();
        MessageBox.Show("Text File Saved");
    }
}

XAML looks like below,

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition />
    </Grid.RowDefinitions>
    <Button Content="Save" Margin="20 10" Command="{Binding SaveCommand}" CommandParameter="{Binding ElementName=myRichTextBox, Path=Document}"/>
    <RichTextBox Grid.Row="1" x:Name="myRichTextBox" AcceptsTab="True" Margin="20">
        <FlowDocument>
            <Paragraph>
                <Run>Some Paragraph</Run>
            </Paragraph>
        </FlowDocument>
    </RichTextBox>
</Grid>

Upvotes: 6

Related Questions