1

There are pictures of what I want to achieve in this question.

I tried putting the TextBlock and the Button in a WrapPanel, and this works for single-line text but not for multi-line text.

<WrapPanel>
    <TextBlock
       TextTrimming="WordEllipsis"
       TextWrapping="WrapWithOverflow" .../>
    <Button .../>
</WrapPanel>

The picture below shows what's happening. When the TextBlock text becomes 2 lines the second line takes the whole width of the first line, which is logical. enter image description here

I thought of chopping the string by words and using an ItemsControl with WrapPanel as ItemsPanel. But the text may become longer, and there isn't space for more than 2 lines, that's why I put the TextTrimming="WordEllipsis" there; the remaining text will be trimmed and the button will be at the end of the second line, in that case.

Update: Well it turned out to be not so easy, I went with changing my UI to something simpler like putting a rounded button on the right.

Hossein Ebrahimi
  • 632
  • 10
  • 20

1 Answers1

1

If you don't mind to use TextBox insteaf of TextBlock, it has TextBox.GetRectFromCharacterIndex method to get the rectangle of character by index number and you can utilize it to adjust the position of Button accordingly.

The following is just a proof of concept and there is much room to modify.

Xaml:

<Grid Width="200" Height="100">
    <TextBox x:Name="textBox"
             TextWrapping="WrapWithOverflow" AcceptsReturn="True"
             TextChanged="TextBox_TextChanged"/>
    <Button x:Name="button"
            HorizontalAlignment="Left" VerticalAlignment="Top"
            Content="END" Padding="0" VerticalContentAlignment="Center"/>
</Grid>

Code behind:

private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
    AdjustButtonPosition();
}

private void AdjustButtonPosition()
{
    if (this.textBox is null || this.button is null)
        return;

    var index = textBox.Text.Length;
    var rect = textBox.GetRectFromCharacterIndex(index);

    button.Margin = new Thickness(rect.Right, rect.Top, 0, 0);
    button.Height = rect.Height;
}
emoacht
  • 2,764
  • 1
  • 13
  • 24