コピー元となる Canvas のイメージは VisualBrush で取得します。
VisualBrush brush = new VisualBrush(this.AdornedElement);
コピー元の Canvas と同じサイズの矩形をつくっておいて、この VisualBrushで塗りつぶします。
SimpleAdorner.cs
using System.Windows;using System.Windows.Documents;
using System.Windows.Media;
namespace WpfApplication4
{
public class SimpleAdorner : Adorner
{
public SimpleAdorner(UIElement adornedElement)
: base(adornedElement)
{
}
protected override void OnRender(DrawingContext drawingContext)
{
Point point = new Point(60, 40);
Rect rect = new Rect(point, this.AdornedElement.DesiredSize);
VisualBrush brush = new VisualBrush(this.AdornedElement);
brush.Opacity = 0.3;
drawingContext.DrawRectangle(brush, null, rect);
}
}
}
MainWindow.xaml
<Window x:Class="WpfApplication4.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="200" Width="200">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Orientation="Horizontal">
<Button Click="addButton_Click">Add</Button>
<Button Click="removeButton_Click">Remove</Button>
</StackPanel>
<Canvas Grid.Row="1" Name="baseCanvas" >
<Canvas Name="innerCanvas1" Height="30" Width="40" Top="20" Left="20" Background="Black">
<TextBlock Foreground="White">装飾</TextBlock>
</Canvas>
</Canvas>
</Grid>
</Window>
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="200" Width="200">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Orientation="Horizontal">
<Button Click="addButton_Click">Add</Button>
<Button Click="removeButton_Click">Remove</Button>
</StackPanel>
<Canvas Grid.Row="1" Name="baseCanvas" >
<Canvas Name="innerCanvas1" Height="30" Width="40" Top="20" Left="20" Background="Black">
<TextBlock Foreground="White">装飾</TextBlock>
</Canvas>
</Canvas>
</Grid>
</Window>
MainWindow.xaml.cs
using System.Windows;
using System.Windows.Documents;
namespace WpfApplication4
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void addButton_Click(object sender, RoutedEventArgs e)
{
AdornerLayer layer = AdornerLayer.GetAdornerLayer(this.baseCanvas);
if (layer.GetAdorners(this.innerCanvas1) == null)
{
SimpleAdorner adorner = new SimpleAdorner(this.innerCanvas1);
layer.Add(adorner);
}
}
private void removeButton_Click(object sender, RoutedEventArgs e)
{
AdornerLayer layer = AdornerLayer.GetAdornerLayer(this.baseCanvas);
if (layer.GetAdorners(this.innerCanvas1) != null)
{
layer.Remove(layer.GetAdorners(this.innerCanvas1)[0]);
}
}
}
}
0 件のコメント:
コメントを投稿