WPF 依赖属性,用户控件依赖属性
//定义依赖属性,类必须继承 DependencyObject public class Student : DependencyObject { //定义依赖属性 Name+Property为后缀 public static readonly DependencyProperty NameProperty = DependencyProperty.Register("Name",typeof(string),typeof(Student)); }
调用 Student s = new Student(); s.SetValue(Student.NameProperty,"111"); TextBox1.SetValue(TextBox.TextProperty,s.GetValue(Student.NameProperty));
一、用户控件 依赖属性 效果:动画数字从100到200
代码: 1、用户控件 ShowNumberControl <UserControl x:Class="WpfApplication1.ShowNumberControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"> <Grid> <Label x:Name="numberDisplay" Height="50" Width="200" Background="LightBlue"/> </Grid> </UserControl> 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 WpfApplication1 { /// <summary> /// ShowNumberControl.xaml 的交互逻辑 /// </summary> public partial class ShowNumberControl : UserControl { public ShowNumberControl() { InitializeComponent(); } public int CurrentNumber { get { return (int)GetValue(CurrentNumberProperty); } set { SetValue(CurrentNumberProperty,value); } } //依赖属性 public static readonly DependencyProperty CurrentNumberProperty = DependencyProperty.Register("CurrentNumber",typeof(int),typeof(ShowNumberControl),new UIPropertyMetadata(100,new PropertyChangedCallback(CurrentNumberChanged)),new ValidateValueCallback(ValidateCurrentNumber) ); //验证值 public static bool ValidateCurrentNumber(object value) { if (Convert.ToInt32(value) >= 0 && Convert.ToInt32(value) <= 500) return true; else return false; } //当前数字改变后 public static void CurrentNumberChanged(DependencyObject d,DependencyPropertyChangedEventArgs e) { ShowNumberControl c = (ShowNumberControl)d; Label theLabel = c.numberDisplay; theLabel.Content = e.NewValue.ToString(); } } } 2、窗体调用 用户控件 <Window x:Class="WpfApplication1.Window3" (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |