Show popup under text in TextBox
I had a question the other day about someone who wanted to add a popup menu under a certain line / word of text. Here is the solution:
In the XAML we have the following markup:
<Grid>
<RichTextBox x:Name="richtTextBox" Height="400" VerticalAlignment="Top"/>
<Button HorizontalAlignment="Left" VerticalAlignment="Bottom" Click="testButton_Click" Content="qdfsdfsfsdf"/>
</Grid>
Then in the constructor of the page I insert some text in the textbox:
richtTextBox.Selection.Text =
"Lorem ipsum pro falli dicunt volumus te, ex velit probatus corrumpit per. His ex reque aperiam alienum, liber indoctum per an. Sed ei nibh cibo minim, et eam graeci suavitate. Vim iusto gubergren repudiandae ei.";
Then when the user clicks the button, the popup opens up under the selected text:
private void testButton_Click(object sender, RoutedEventArgs e)
{
var rect = richtTextBox.Selection.Start.GetCharacterRect(System.Windows.Documents.LogicalDirection.Forward);
var richtTextBoxPosition =
richtTextBox.TransformToVisual(Application.Current.RootVisual).Transform(new Point(0, 0));
var popup = new Popup()
{
HorizontalOffset = richtTextBoxPosition.X + rect.X,
VerticalOffset = richtTextBoxPosition.Y + rect.Y + richtTextBox.FontSize,
Height = 150,
Width = 100
};
popup.Child = new ListBox()
{
Background = new SolidColorBrush(Colors.Red),
Height = 150,
Width = 100
}; // use your custom UC here
popup.IsOpen = true;
}
You can tweak the code and set the selection in code behind so.
Have fun and till next post.
Geen opmerkingen:
Een reactie posten