一、概要
我们将会通过一个简单的综合例子来阐述下依赖属性的变化。
场景:我们在一个文本框中输入一个数字,然后对应的panel中会出现对应的椭圆,椭圆的个数与输入的文本相同。
我们在MainWindow中定义一个名字叫CountProperty的依赖属性,该属性关联到一个回调方法OnCountChanged,当依赖属性发生变化的时候,会触发该方法。
在文本框的事件处理程序来动态修改依赖属性的值,使回调方法OnCountChanged触发,然后在这个函数中画出椭圆。
参考代码如下:
1 using System.Windows; 2 using System.Windows.Controls; 3 using System.Windows.Media; 4 using System.Windows.Shapes; 5 6 namespace DependencyDemo 7 { 8 /// <summary> 9 /// Interaction logic for MainWindow.xaml 10 /// </summary> 11 public partial class MainWindow : Window 12 { 13 public MainWindow() 14 { 15 InitializeComponent(); 16 } 17 public int Count 18 { 19 get { return (int)GetValue(CountProperty); } 20 set { SetValue(CountProperty, value); } 21 } 22 23 // Using a DependencyProperty as the backing store for Count. This enables animation, styling, binding, etc... 24 public static readonly DependencyProperty CountProperty = 25 DependencyProperty.Register("Count", typeof(int), typeof(MainWindow), new FrameworkPropertyMetadata(new PropertyChangedCallback(OnCountChanged))); 26 27 public static void OnCountChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 28 { 29 MainWindow win = d as MainWindow; 30 win.wrapPanel?.Children.Clear(); 31 int myCount = (int)e.NewValue; 32 for (int i = 0; i < myCount; i++) 33 { 34 win.wrapPanel?.Children.Add(new Ellipse() { Height = 20, Width = 20, Stroke = Brushes.Red, Margin = new Thickness(1) }); 35 } 36 } 37 38 private void TextBox_TextChanged(object sender, TextChangedEventArgs e) 39 { 40 int myCount = 0; 41 bool isSuccess = int.TryParse(this.tbInput.Text, out myCount); 42 if(isSuccess && myCount > 0) 43 { 44 Count = myCount; 45 } 46 } 47 } 48 }
1 <Window x:Class="DependencyDemo.MainWindow" 2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 4 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 5 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 6 xmlns:local="clr-namespace:DependencyDemo" 7 mc:Ignorable="d" 8 Title="MainWindow" Height="350" Width="315"> 9 <Grid> 10 <Grid.RowDefinitions> 11 <RowDefinition Height="21*"/> 12 <RowDefinition Height="139*"/> 13 </Grid.RowDefinitions> 14 <StackPanel Orientation="Horizontal"> 15 <Label Content="椭圆个数:" FontSize="16"></Label> 16 <TextBox Width="200" Margin="5" TextChanged="TextBox_TextChanged" Name="tbInput"></TextBox> 17 </StackPanel> 18 <ScrollViewer Grid.Row="1"> 19 <WrapPanel Name="wrapPanel" > 20 </WrapPanel> 21 </ScrollViewer> 22 </Grid> 23 </Window>
运行结果如下: