Search code examples
c#wpfxamltextblockclipping

How to clip textblock inside proportional grid?


In a UserControl that's inside a ListBox, I've got a TextBlock with proportional width (Width="*") inside a Grid that I want to take the remaining width of the grid, but whenever I resize the ListBox to a size that would clip that TextBlock's content I get a scroll bar. How can I clip the TextBlock width so that I don't get an horizontal scroll bar? Ideally clipping it with ellipsis.

EDIT: Forgot to mention the ListBox.


Solution

  • The listbox is scrolling because it's default behavior is to have HorizontalScrollBarVisibility to Auto.

    Try setting this property to disabled:

    <ListBox ScrollViewer.HorizontalScrollBarVisibility="Disabled">
    

    As for clipping to an ellipse, this is more complex. You can clip to an ellipsis quite easily using the Clip property:

                <TextBlock Text="Some very long thing that I'm putting in here to clip" Background="Blue">
                    <TextBlock.Clip>
                        <EllipseGeometry Center="100,8" RadiusX="100" RadiusY="8" />
                    </TextBlock.Clip>
                </TextBlock>
    

    However, to keep the Center, RadiusX and RadiusY in order you'll have to bind it to the height and width of the text box (perhaps using a converter to half these values).