views:

27

answers:

2

Hello all,

I am trying to convert my WPF application into a WPF UserControl. In the original application, I had intentionally modified the margins of certain elements so that their edges were not within the bounds of the window. I did this in order to hide undesirable borders that I could not get rid of without having to write my own control template. It was a simple fix, but unfortunately this technique is not working when my application is made into a UserControl. If I set the width of my UserControl to the same width as the window in my original application, when I view this UserControl within a test application, the elements whose borders I wanted to hide are now fully visible.

It doesn't make sense to me why this would happen. If I set the width of the UserControl to a certain WIDTH, then the width of the UserControl should be equal to WIDTH, right? Well, as you can see below in Image 1, all the elements of the UserControl are fully visible, no matter what I set WIDTH to be. The desired visual (the one I used to get in the original application) is shown in Image 2, where the elements are properly cut off by the boundaries of the window.

My Problem

How can I ensure that elements with negative margins will display the way I want them to in a UserControl? Any help on accomplishing this would be greatly appreciated.

Thank you so much,

Dalal

+1  A: 

Have you tried setting the ClipToBounds property on your elements within your UserControl to True?

Scott
ClipToBounds did the trick. Thanks.
Dalal
+1  A: 

Inside your user control, set the Clip property of the container , for example Grid to the size(width, height) of user control .

For example,

<Window x:Class="TestClipping.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="Auto" Width="Auto">
    <Grid SizeChanged="OnGridSizeChanged"
          x:Name="myGrid">

    </Grid>
</Window>

and the event handler:

private void OnGridSizeChanged(object sender, SizeChangedEventArgs e)
{
    // Set the clipping region to match the current display region of the grid.
    var visibleArea = new RectangleGeometry();
    visibleArea.Rect = new Rect(0, 0,
    myGrid.ActualWidth, myGrid.ActualHeight);
    myGrid.Clip = visibleArea;
}
DrakeVN