简体   繁体   中英

How to force a control to stay within the window in wpf?

I have a wpf app where there is a grid and in there is one button. Each time you go on the button with your mouse, it goes to another random place. The resizing works great, until the button places on the bottom right side and after resizing it just dissapears

<Grid x:Name="MainGrid" MinWidth="60" MinHeight="60" Margin="0">
    <Button x:Name="btn" Content="Button" Click="Button_Click" MouseEnter="MouseEnter_btn" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="0,0,67,149"/>
</Grid>

    private void MouseEnter_btn(object sender, MouseEventArgs e)
    {
        Random rng = new Random();
        double x = (MainGrid.ActualWidth - btn.ActualWidth) - rng.Next(1, (int)(MainGrid.ActualWidth - btn.ActualWidth));
        double y = (MainGrid.ActualHeight - btn.ActualHeight) - rng.Next(1, (int)(MainGrid.ActualHeight - btn.ActualHeight));
        btn.Margin = new Thickness(x, y, 1, 1);
    }

Here's a solution that should do pretty much what you are looking for:

<Grid x:Name="MainGrid">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="100" x:Name="XOffset"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="100" x:Name="YOffset"/>
    </Grid.RowDefinitions>

    <Button x:Name="btn" Content="Button" 
            MouseEnter="MouseEnter_btn"
            Grid.Row="1"
            Grid.Column="1"/>
</Grid>

And in code just change the XOffset and YOffset

private void MouseEnter_btn(object sender, MouseEventArgs e)
{
    Random rng = new Random();
    Size availableSize = new Size(MainGrid.ActualWidth - btn.ActualWidth, MainGrid.ActualHeight - btn.ActualHeight);

    int x = rng.Next(1,(int)availableSize.Width);
    int y = rng.Next(1, (int)availableSize.Height);

    XOffset.Width = new GridLength(x);
    YOffset.Height = new GridLength(y);
}

Now the button is locked to the bottom right with XOffset and YOffset and if it gets to the left or top edge it will stay there and the right/bottom offset will be decreased.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM