Hi,@Paolo Mossa. Welcome to Microsoft Q&A Forum.
If you want to translate the WPF content in RichTextBox to a format that can be used in a Windows Forms RichTextBox, you could leverage the System.Windows.Forms.RichTextBox
for this purpose.
app.csproj:
<PropertyGroup>
...
<UseWPF>true</UseWPF>
<UseWindowsForms>true</UseWindowsForms>
</PropertyGroup>
MainWindow.xaml:
<Window x:Class="RichTextBoxRTF.MainWindow"
xmlns:local="clr-namespace:RichTextBoxRTF"
xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<RichTextBox Name="rtb" HorizontalAlignment="Center" Height="200" VerticalAlignment="Center" Width="300" BorderBrush="Gray" Padding="5,-2,-5,-2">
<FlowDocument>
<BlockUIContainer>
<Image Source="E:\repos\1204\RichTextBoxRTF\1.PNG" Width="300" Height="100"/>
</BlockUIContainer>
<Paragraph>hhhhhhhhhhh</Paragraph>
<Paragraph>hhhhhhhhhhhnnnnnn</Paragraph>
</FlowDocument>
</RichTextBox>
<WindowsFormsHost Grid.Column="1">
<wf:RichTextBox x:Name="wfrtb">
</wf:RichTextBox>
</WindowsFormsHost>
</Grid>
</Window>
MainWindow.xaml.cs:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
string winFormsRtf = RtfTranslator.TranslateWpfRtfToWinFormsRtf(rtb);
wfrtb.Rtf = winFormsRtf;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
}
}
public static class RtfTranslator
{
public static string TranslateWpfRtfToWinFormsRtf(System.Windows.Controls.RichTextBox wpfRichTextBox)
{
TextRange textRange = new TextRange(wpfRichTextBox.Document.ContentStart, wpfRichTextBox.Document.ContentEnd);
using (MemoryStream stream = new MemoryStream())
{
textRange.Save(stream, DataFormats.Rtf);
stream.Seek(0, SeekOrigin.Begin);
using (StreamReader reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
}
The result:
Remember that Windows Forms and WPF formats may have some differences, especially when dealing with embedded objects or advanced formatting. Make sure to test and adjust accordingly based on your specific requirements.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.