XAML和C#
实现相同的窗体的两种语言的源码
<Window Title="XAML 窗口" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Width = "300" Height="200" >
<DockPanel>
<Button DockPanel.Dock="Left"
Background="AliceBlue" Margin="0 5 0 10" Content="Hello XAML"/>
<Button >
<!--������DockPanel��������Button-->
<DockPanel.Dock>
Right
</DockPanel.Dock>
<Button.Background>
<LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
<GradientStop Color="Yellow" Offset="0.0" />
<GradientStop Color="Red" Offset="0.25" />
<GradientStop Color="Blue" Offset="0.75" />
<GradientStop Color="LimeGreen" Offset="1.0" />
</LinearGradientBrush>
</Button.Background>
Hello XAML
</Button>
</DockPanel>
</Window>
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace mumu_windowcs
{
public class MyWindow : Window
{
[STAThread]
public static void Main()
{
MyWindow win = new MyWindow();
win.Show();
Application app = new Application();
app.Run();
}
public MyWindow()
{
InitializeComponent();
}
private void InitializeComponent()
{
this.Title = "XAML窗口";
this.Width = 300;
this.Height = 200;
DockPanel panel = new DockPanel();
Button btn = new Button();
btn.Content = "Hello XAML";
btn.Background = new SolidColorBrush(Colors.AliceBlue);
btn.Margin = new Thickness(0, 5, 0, 10);
DockPanel.SetDock(btn, Dock.Left);
panel.Children.Add(btn);
Button btn2 = new Button();
btn2.Content = "Hello XAML";
LinearGradientBrush brush = new LinearGradientBrush();
brush.StartPoint = new Point(0, 0);
brush.EndPoint = new Point(1, 1);
brush.GradientStops.Add(new GradientStop(Colors.Yellow, 0));
brush.GradientStops.Add(new GradientStop(Colors.Red, 0.25));
brush.GradientStops.Add(new GradientStop(Colors.Blue, 0.75));
brush.GradientStops.Add(new GradientStop(Colors.LimeGreen, 1));
btn2.Background = brush;
DockPanel.SetDock(btn2, Dock.Right);
panel.Children.Add(btn2);
this.Content = panel;
}
}
}
XAML文件有两个重要组成部分:一是有完整的开始和结束标签的要素,如Window,DockPanel和Button等,称为“元素”(Element);二是依附于元素的要素,如Width,Height和Background等,称为“属性”(Attribute).
在XAML需要命名空间:xmlns=“http://schemas.microsoft.com/winfx/2006/xaml/presentation”
命名空间以及映射
在WPF中只有4种元素可以作为根元素
- Window:一个窗体
- Page:页面
- Application:一个应用程序
- ResourceDictionary:代表一个逻辑资源的集合

其他的命名空间
- 系统命名空间:xmlns:s =“clr-namespace:System;assembly=mscorlib.dll”
- 自定义类
2-1. 本地的自定义类:xmlns:local =“clr-namespace:mumu_customnamespace”
2-2. 外部程序的自定义类:xmlns:customlib =“clr-namespace:mumu_custolib;assembly = mumu_customlib”
简单属性
- 直接赋值的,比如像“Title”和“Width”.
- 相当于c#中枚举型,直接字符赋值就行,比如
C#
solidbrush.Color= Colors.AliceBlue;
XAML
<Button
XAML与C#混合编程

本文介绍XAML和C#在WPF开发中的混合使用技巧,覆盖元素、属性、依赖属性等内容,并详解如何实现资源引用、样式、动画及数据绑定等功能。
最低0.47元/天 解锁文章
634

被折叠的 条评论
为什么被折叠?



