WPF instance show -- how to obtain the image of the UI element
The title is hard to explain. Let me explain it again.
For example, I want to drag an element on the UI. During the drag process, I need to move the shadow of the UI element with the mouse (but the UI remains in the original position). When I open the mouse, the UI element is moved to a new location.
This is a common requirement. The first step to achieve this requirement is to obtain the picture of this UI element. This step is actually very simple. The core is to use the image brush subclass visualbrush.
The following is a simple example.
This is the UI description,
- <Window X: class = "wpfapplicationimage. window1"
- Xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- Xmlns: x = "http://schemas.microsoft.com/winfx/2006/xaml"
- Title = "window1" Height = "300" width = "400" background = "steelblue">
- <Grid margin = "10">
- <Grid. columndefinitions>
- <Columndefinition width = "160" type = "codeph" text = "/codeph"/>
- <Columndefinition width = "*"/>
- <Columndefinition width = "160" type = "codeph" text = "/codeph"/>
- </Grid. columndefinitions>
- <Stackpanel X: Name = "stackpanelleft" background = "white">
- <Button X: Name = "BTN" content = "OK" Height = "40"/>
- </Stackpanel>
- <Button content = ">" grid. Column = "1" margin = "5" Click = "button_click"/>
- <Stackpanel X: Name = "stackpanelright" background = "white" grid. Column = "2"/>
- </GRID>
- </WINDOW>
The UI effect is as follows:
Click the button in the middle to add the image of the button in the left stackpanel to the stackpanel on the right. The Code is as follows (the core is to use visualbrush ):
- Private void button_click (Object sender, routedeventargs E)
- {
- Visualbrush vbrush = new visualbrush (BTN );
- Rectangle rect = new rectangle ();
- Rect. width = BTN. width;
- Rect. Height = BTN. height;
- Rect. Fill = vbrush;
- Rect. Opacity = 0.5; // to indicate the image, I set the opacity to 50%
- This. stackpanelright. Children. Add (rect );
- }
Click a few and the result is as follows:
The core problem is solved, and the rest is easy. If you want to perform drag-and-drop operations, you can only use the mouse event and offset calculation tips: P
==========================================
I wrote a complete example and uploaded it to the resource. Unfortunately, I don't know why it cannot be displayed. The name is "WPF drag effect source code ". When I can see it myself, I will post the link ~~~
Place a prefix ~~~~