无Xaml的WPF展示

时间:2022-01-04 02:13:17

我们创建一个wpf应用程序,我们把里面的xaml文件全部删除,添加一个新类:

如下图:无Xaml的WPF展示

然后我们cs文件中的代码:

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Media;
using System.Windows.Shapes; namespace 无xaml的WPF
{
//首先继承System.Windows.Application对象
class subMain : System.Windows.Application
{
//线程单元标记
[STAThread]
public static void Main()
{ System.Windows.Application app = new Application();
MyWindow mw = new MyWindow();
mw.Width = ;
mw.Height = ;
mw.BorderThickness = new Thickness(, , , );
app.Run(mw);
}
} public partial class MyWindow : Window//继承Window对象
{
//创建需要的元素
Canvas canv;
Ellipse e1;
Button b1;
Label lab1;
Rectangle r1;
Rectangle r2;
public MyWindow()
{
canv = new Canvas();
canv.Name = "C1";
this.Content = canv;
canv.Margin = new Thickness(, , , );
canv.Background = new SolidColorBrush(Colors.White); e1 = new Ellipse();
e1.Fill = new SolidColorBrush(Colors.YellowGreen);
e1.Stroke = new SolidColorBrush(Colors.Azure);
e1.Width = ;
e1.Height = ;
e1.Margin = new Thickness(, , , );
canv.Children.Add(e1); r1 = new Rectangle();
r1.Fill = new SolidColorBrush(Colors.Tomato);
r1.Opacity = 0.5;
r1.Stroke = new SolidColorBrush(Colors.Red);
r1.Width = ;
r1.Height = ; r1.SetValue(Canvas.LeftProperty, (double));
r1.SetValue(Canvas.TopProperty, (double));
canv.Children.Add(r1); b1 = new Button();
b1.Width = ;
b1.Height = ;
b1.Content = "修改圆形位置";
b1.SetValue(Canvas.LeftProperty, (double)r1.GetValue(Canvas.LeftProperty) + );
b1.SetValue(Canvas.TopProperty, (double)r1.GetValue(Canvas.TopProperty) + );
b1.Click += new RoutedEventHandler(b1_Click);
canv.Children.Add(b1); Label lab0 = new Label();
lab0.Margin = new Thickness(, , , );
lab0.Width = ;
lab0.Height = ;
lab0.FontSize = ;
lab0.Name = "lab0";
lab0.Content = "无XAML动态编程演示";
canv.Children.Add(lab0); lab1 = new Label();
lab1.Margin = new Thickness(, , , );
lab1.Width = ;
lab1.Height = ;
lab1.FontSize = ;
lab1.Name = "lab1";
lab1.Content = "Location:";
canv.Children.Add(lab1); r2 = new Rectangle(); r2.Width = ;
r2.Height = ;
r2.Fill = Brushes.YellowGreen;
r2.Stroke = Brushes.RoyalBlue;
r2.StrokeThickness = ;
canv.Children.Add(r2); e1.MouseMove += new System.Windows.Input.MouseEventHandler(el_MouseMove);
} void b1_Click(object sender, RoutedEventArgs e)
{
Point p = System.Windows.Input.Mouse.GetPosition(canv as System.Windows.IInputElement);
e1.Margin = new Thickness(p.X, p.Y, , ); } void el_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
{
Ellipse a = e.Source as Ellipse;
Point p = System.Windows.Input.Mouse.GetPosition(canv as System.Windows.IInputElement);
lab1.Content = "Location:" + p.ToString();
} }
}

效果展示:无Xaml的WPF展示