使用Silverlight 2的Canvas,写了
一个动态创建Rectangle的示例,由于时
间的原因所以难免有些
不足之处,但程序
功能都正常使用.用鼠标可以点击画布任何位置拖出
一个矩形对象,松开鼠标即可完成
一个矩形的创建!
<UserControl x:Class="Sample.dragrect"
xmlns="
http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="
http://schemas.microsoft.com/winfx/2006/xaml"
Width="780" Height="400">
<StackPanel
BACkground="Green"
Orientation="Horizontal">
<Canvas x:Name="LayoutRoot"
BACkground="GreenYellow"
Width="650" Height="400"
MouseMove="Canvas_MouseMove"
Mou@R_
450_10288@ftButtonDown="Canvas_Mou@R_
450_10288@ftButtonDown"
Mou@R_
450_10288@ftButtonUp="Canvas_Mou@R_
450_10288@ftButtonUp"/>
<StackPanel
BACkground="Gold" Margin="10">
<TextBlock Text="选择颜色:"/>
<Button x:Name="btnRed"
Width="100" Height="50"
FontSize="20" Content="Red" Margin="5"
Click="btnRed_Click"/>
<Button x:Name="btnBlue"
Width="100" Height="50"
FontSize="20" Content="Blue" Margin="5"
Click="btnBlue_Click"/>
<Button x:Name="btnGreen"
Width="100" Height="50"
FontSize="20" Content="Green" Margin="5"
Click="btnGreen_Click"/>
<Button x:Name="btnClear"
Width="100" Height="50"
FontSize="20" Content="Clear" Margin="5"
BACkground="Red"
Click="btnClear_Click"/>
</StackPanel>
</StackPanel>
</UserControl>
C#
代码:
namespace Sample
{
public partial class dragrect : UserControl
{
public dragrect()
{
InitializeComponent(
);
}
bool mouseMoveing =
false;
Point mousePoint;
Color rectColor = Color
s.Red;
private void Canvas_MouseMove(ob
ject sender,MouseEventArgs
E)
{
//如果鼠标没有拖动矩形则返回
if (!mouseMoveing)
return;
//
获取鼠标当前坐标
Point curPos = e.GetPosition(
null);
//取得最小坐标值
double
posx = mousePoint.X;
double
posy = mousePoint.Y;
//计算矩形的宽和高
double rectWidth = Math.Abs(curPo
s.X - mousePoint.
X);
double rectHeight = Math.Abs(curPo
s.Y - mousePoint.Y
);
//创建一个矩形元素
Rectangle rect = new Rectangle(
);
//声明矩形的宽和高
rect.Width = rectWidth;
rect.Height = rectHeight;
//填充颜色
rect.Fill = new SolidColorBrush(rectColor
);
//声明矩形在Canvas中创建的位置
Canva
s.SetLeft(rect,
posx);
Canva
s.SetTop(rect,
posy);
//
添加矩形到Canvas中
LayoutRoot.Children.Add(rect
);
}
private void Canvas_Mou@R_
450_10288@ftButtonDown(ob
ject sender,MouseButtonEventArgs
E)
{
//
获取当前的鼠标位置
mousePoint = e.GetPosition(
null);
//开始创建矩形
mouseMoveing = true;
}
private void Canvas_Mou@R_
450_10288@ftButtonUp(ob
ject sender,MouseButtonEventArgs
E)
{
//矩形创建完成
mouseMoveing =
false;
}
private void btnRed_Click(ob
ject sender,RoutedEventArgs
E)
{
//声明矩形颜色为Red
rectColor = Color
s.Red;
}
private void btnBlue_Click(ob
ject sender,RoutedEventArgs
E)
{
//声明矩形颜色为Blue
rectColor = Colors
.blue;
}
private void btnGreen_Click(ob
ject sender,RoutedEventArgs
E)
{
//声明矩形颜色为Green
rectColor = Color
s.Green;
}
private void btnClear_Click(ob
ject sender,RoutedEventArgs
E) { //清除所有Canvas内的矩形元素
LayoutRoot.Children.Clear(
); } } }