3

Since Silverlight doesn't have the comfy feature of 'ClipToBounds' properties on controls, I have to define clipping shapes by myself. I was wondering if I could create a clipping rectangle that's following the size of my control. Any suggestions?

Tenshiko
  • 1,450
  • 3
  • 17
  • 33

2 Answers2

3

If there is an existing control in you layout that you want to dynamically clip then use its SizeChanged event. For example lets say you want to clip this Grid:-

    <Grid SizeChanged="Grid_SizeChanged" Width="50" Height="20">
        <Grid.Clip>
            <RectangleGeometry />
        </Grid.Clip>
        <TextBlock Margin="0 -9 0 0" Text="This text should not be legible" />
    </Grid>

With the code-behind:-

   private void Grid_SizeChanged(object sender, SizeChangedEventArgs e)
    {
        ((RectangleGeometry)((Grid)sender).Clip).Rect = new Rect(0.0, 0.0, e.NewSize.Width, e.NewSize.Height);
    }  

For a your own custom control you might consider handling the clip rectangle in the ArrangeOverride instead of relying on the SizeChanged event. In this case you probably want to assign RectangleGeometry to the Clip property in code rather than relying on it being assigned in the Xaml of the default template.

AnthonyWJones
  • 187,081
  • 35
  • 232
  • 306
  • I made a Behavior for FrameworkElement which does what you've described. Now I have ClipToBounds in Silverlight! :) Exactly what I was looking for! Thank you! – Tenshiko Apr 18 '11 at 09:13
0

Silverlight supports that: try using HorisontalAlignment and vertical alignment propertys. Set them to stretch. If this doesn't work then you will have to post xaml example.

Sonosar
  • 526
  • 2
  • 12
  • The alignment properties do not affect the clip region of a control. – AnthonyWJones Apr 15 '11 at 20:15
  • Will ClipToBounds work if the parent have triangular form?I'm asking this code if your parent is always rectangular then alignment property's are that you are looking for. – Sonosar Apr 16 '11 at 06:35
  • You seem to be quite confused about what the WPF `ClipToBounds` actually does. Its function is about clipping not sizing or alignments. The alignment properties are entirely irrelevant to the question. – AnthonyWJones Apr 16 '11 at 18:33