XAML 将按钮放在1-2行文字结尾之后

bxgwgixi  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(124)

有我想在this question中实现的东西的图片。
我尝试将TextBlockButton放在WrapPanel中,这适用于单行文本,但不适用于多行文本。

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

下图显示了发生的情况。当TextBlock文本变为两行时,第二行占据了第一行的整个宽度,这是合乎逻辑的。

我想把字符串按单词截断,用ItemsControl加上WrapPanel作为ItemsPanel,但是文本可能会变长,而且没有超过2行的空间,所以我把TextTrimming="WordEllipsis"放在那里;在这种情况下,剩余的文本将被修剪,按钮将位于第二行的末尾。
更新:嗯,事实证明这并不那么容易,我把我的用户界面改成了更简单的东西,比如在右边放一个圆形按钮。

eimct9ow

eimct9ow1#

如果您不介意使用TextBox代替TextBlock,它有TextBox.GetRectFromCharacterIndex方法,通过索引号获得字符的矩形,您可以利用它相应地调整Button的位置。
以下只是一个概念证明,还有很大的修改空间。
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>

后面的代码:

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;
}

相关问题