简体   繁体   中英

Bring UserControl in front of Window Foreground

In my WPF Application I have a MainWindow , if a button is clicked a UserControl opens. I want the foreground of the MainWindow to be black (with some opacity). So far so good, I managed to do this. But as the UserControl is displayed in the MainWindow its foreground is the same. So I wanted to know how to get the UC in front so it keeps its foreground.

This is how the UC is used in the MainWindow

<local:PopUp
            x:Name="popUp"
            Grid.Row="0"
            Grid.RowSpan="3"
            Grid.Column="1"
            Grid.ColumnSpan="2"
            HorizontalAlignment="Center"
            VerticalAlignment="Center"
            Visibility="Hidden"/>

This is the part where the button click is noticed, the pop up (UC) appears and the foreground should be changed.

private void Add_Click(object sender, RoutedEventArgs e)
{
    pop.Visibility = Visibility.Visible;
    this.Foreground = Brushes.Black;
    this.Opacity = 0.1;
}

Your usercontroll is named popUp and in the button click event you call pop to be visible. that might be a typo.

In general: If you want an UIelement to be on top of other UIelements you only need to make sure it is the last UIelement in the same container.

Example of the right order for two colored Grid's And a button in the same a grid.(you can play with this and change the order a few times to see the effects.) XAML:

 <Grid x:Name="ContainerGridForAllthreeUIElements">
    <Grid x:Name="BlueGrid" Background="Blue"/>
    <Grid x:Name="RedGrid" Background="Red" Visibility="Collapsed" Margin="40">
        <Viewbox>
            <TextBlock Text=" I'll be back" Margin="10"/>
        </Viewbox>            
    </Grid>
    <Button 
        x:Name="Button_Toggle" 
        Content="Click to toggle"
        Click="Button_Toggle_Click" 
        HorizontalAlignment="Center"
        VerticalAlignment="Center"/>
</Grid>

Code behind:

private void Button_Toggle_Click(object sender, RoutedEventArgs e)
    {
        if(RedGrid.Visibility == Visibility.Collapsed)
        {
            RedGrid.Visibility = Visibility.Visible;
            BlueGrid.Opacity = 0.4;
        }
        else
        {
            BlueGrid.Opacity = 1;
            RedGrid.Visibility = Visibility.Collapsed;
        }
    }

Happy coding.

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