简体   繁体   中英

Bringing a user control to the front in Expression Blend, C#, WPF

I have a window with a Grid on.

On this I have some buttons, one of which when clicked will create a new 'PostIt' which is a user control I have created.

What I want to do is click on a 'PostIt' and have that control on top of all the others.

I have tried...

Grid.SetZIndex(sender, value);

Which seems to be the correct code, no errors, just not movement of the control :(

The problem may lie in the fact that the code for the click is in the user control and not the mainwindow cs file. Does this matter?

The 'PostIt' is simply a border with a text box in it.

Are you calling Grid.SetZIndex(sender, value) in a handler of the PostIt mouse click, or a handler for a control inside the PostIt? What is the value that you are setting?

Here is an example that works:

<UserControl x:Class="WpfApplication1.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300" MouseUp="UserControl_MouseUp">
    <Grid>

    </Grid>
</UserControl>

  public partial class UserControl1 : UserControl
  {
    public UserControl1()
    {
      InitializeComponent();
    }

    private void UserControl_MouseUp(object sender, MouseButtonEventArgs e)
    {
      Panel.SetZIndex(this, Panel.GetZIndex(this) + 2);
    }
  }


<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="350" Width="525">
  <Grid>
    <local:UserControl1 Background="Green" Margin="40,40,100,100" Panel.ZIndex="0" />
    <local:UserControl1 Background="Red" Margin="140,140,10,10" Panel.ZIndex="1" />
  </Grid>
</Window>

Jogy

This may not be the best solution, but it's the one that worked for me; I was re-ordering two grids:

GridOnBottom.SetValue(Grid.ZIndexProperty, (int)GridOnTop.GetValue(Grid.ZIndexProperty) + 1);

...with GridOnBottom and GridOnTop renamed to the instances of the objects you're re-ordering. Granted, it's not the best solution, but it works.

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