<Window x:Class="TestOfAttachProperty.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <StackPanel > <Button Content="OK" Click="Button_Click" /> </StackPanel> </Window>
using System.Windows; namespace TestOfAttachProperty { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { Human human = new Human(); School.SetGrade(human, 6); int grade = School.GetGrade(human); MessageBox.Show(grade.ToString()); } } public class School:DependencyObject { public static int GetGrade(DependencyObject obj) { return (int)obj.GetValue(GradeProperty); } public static void SetGrade(DependencyObject obj, int value) { obj.SetValue(GradeProperty, value); } // Using a DependencyProperty as the backing store for Grade. This enables animation, styling, binding, etc... public static readonly DependencyProperty GradeProperty = DependencyProperty.RegisterAttached("Grade", typeof(int), typeof(School), new UIPropertyMetadata(0)); } public class Human:DependencyObject { } }
------------------------------------------------------------------------------------
C#代码写布局
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace TestOfGridCSharp { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); InitializeLayout(); } private void InitializeLayout() { // 构造Grid Grid grid = new Grid() { ShowGridLines = true }; // 定义Grid grid.ColumnDefinitions.Add(new ColumnDefinition()); grid.ColumnDefinitions.Add(new ColumnDefinition()); grid.ColumnDefinitions.Add(new ColumnDefinition()); grid.RowDefinitions.Add(new RowDefinition()); grid.RowDefinitions.Add(new RowDefinition()); grid.RowDefinitions.Add(new RowDefinition()); // 初始化Button Button button = new Button() { Content = "OK" }; // 设置Button位置 Grid.SetColumn(button,1); Grid.SetRow(button,1); // 将按钮放入Grid中 grid.Children.Add(button); // 将Grid放入窗体中 this.Content = grid; } } }