【WPF】自定义类作为UserControl的依赖属性的binding问题!!!
定义一个类:
public class Student : DependencyObject { public string Name { get { return (string)GetValue(NameProperty); } set { SetValue(NameProperty, value); } } // Using a DependencyProperty as the backing store for Name. This enables animation, styling, binding, etc... public static readonly DependencyProperty NameProperty = DependencyProperty.Register("Name", typeof(string), typeof(Student)); }
public partial class UsercontrolBinding : UserControl { public UsercontrolBinding() { InitializeComponent(); stu = new Student(); stu.Name = "ABC"; tb1.SetBinding(TextBox.TextProperty, new Binding("Name") { Source = stu }); tb2.SetBinding(TextBlock.TextProperty, new Binding("TecName") { Source = this }); } public Student stu { get { return (Student)GetValue(stuProperty); } set { SetValue(stuProperty, value); } } // Using a DependencyProperty as the backing store for stu. This enables animation, styling, binding, etc... public static readonly DependencyProperty stuProperty = DependencyProperty.Register("stu", typeof(Student), typeof(UsercontrolBinding)); public string TecName { get { return (string)GetValue(TecNameProperty); } set { SetValue(TecNameProperty, value); } } // Using a DependencyProperty as the backing store for TecName. This enables animation, styling, binding, etc... public static readonly DependencyProperty TecNameProperty = DependencyProperty.Register("TecName", typeof(string), typeof(UsercontrolBinding)); }
<StackPanel> <TextBox x:Name="tb1" Text="demo"/> <TextBlock x:Name="tb2" Text="demo"/> </StackPanel>
public MainWindow() { InitializeComponent();stuB = new Student() { Name="Zhang", }; TecName = "TecYang"; ub1.SetBinding(UsercontrolBinding.TecNameProperty, new Binding("TecName") { Source = this });ub1.SetBinding(UsercontrolBinding.stuProperty, new Binding("stuB") { Source = this });}public string TecName { get { return (string)GetValue(TecNameProperty); } set { SetValue(TecNameProperty, value); } } // Using a DependencyProperty as the backing store for TecName. This enables animation, styling, binding, etc... public static readonly DependencyProperty TecNameProperty = DependencyProperty.Register("TecName", typeof(string), typeof(MainWindow));public Student stuB { get { return (Student)GetValue(stuBProperty); } set { SetValue(stuBProperty, value); } } // Using a DependencyProperty as the backing store for stuB. This enables animation, styling, binding, etc... public static readonly DependencyProperty stuBProperty = DependencyProperty.Register("stuB", typeof(Student), typeof(MainWindow));