I have a WinUI 3 RichEditBox
, and I need it to have scroll bars. I have to insert it programatically in C#, not XAML. I am putting it in a Grid
with three rows, which are defined like this:
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
I tried inserting it in a ScrollViewer
, like this:
Variables.textViews[tabIndex].HorizontalAlignment = HorizontalAlignment.Stretch;
Variables.textViews[tabIndex].VerticalAlignment = VerticalAlignment.Stretch;
ScrollViewer scrollViewer = new() {
Content = Variables.textViews[tabIndex]
};
Grid.SetRow(scrollViewer, 2);
Grid.SetColumn(scrollViewer, 0);
scrollViewer.VerticalAlignment = VerticalAlignment.Stretch;
scrollViewer.HorizontalAlignment = HorizontalAlignment.Stretch;
mainPageGrid.Children.Add(scrollViewer);
I notice that when I press and hold enter, the RichEditBox expands not quite fast enough, causing a scroll bar to appear. When I stop, the scroll bar shows, but without a "thumb" (the part to drag to scroll the edit box). See screenshot below:
I tried to set up a tester project, and kept it simple. After some playing around, I discovered that the solution was to put in Width
and Height
attributes into the initialization of the ScrollViewer
. This is what I came up with:
ScrollViewer scrollViewer = new() {
Content = Variables.textViews[tabIndex],
Width = 100,
Height = 100,
ZoomMode = ZoomMode.Enabled,
HorizontalScrollMode = ScrollMode.Enabled,
HorizontalScrollBarVisibility = ScrollBarVisibility.Auto,
VerticalScrollMode = ScrollMode.Enabled,
VerticalScrollBarVisibility = ScrollBarVisibility.Visible
};
This added scroll bars but kept the component's size at 100x100. See image:
I need the RichEditBox
to fill all the available space. How would I do this?
This is the minimal code that works. The ScrollViewer
, which has a RichEditBox
in it, takes all the available space in the 3rd row.
MainPage.xaml
<Grid x:Name="RootGrid">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
</Grid>
MainPage.xaml.cs
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
RichEditBox richEditBox = new();
ScrollViewer scrollViewer = new()
{
Content = richEditBox,
};
Grid.SetRow(scrollViewer, 2);
RootGrid.Children.Add(scrollViewer);
}
}