1
I’m trying to understand the feature of dependency properties. I’ve read some tutorials on msdn but the feature is still unclear to me.
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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 WpfApplication3 {
/// <summary>
/// Interaction logic for UserControl1.xaml
/// </summary>
public partial class UserControl1 : UserControl {
public UserControl1() {
InitializeComponent();
}
public static readonly DependencyProperty
SetTextProperty = DependencyProperty.Register("SetText", typeof(string),
typeof(UserControl1), new PropertyMetadata("", new PropertyChangedCallback(OnSetTextChanged)));
public string SetText {
get {return(string) GetValue(SetTextProperty); }
set {SetValue(SetTextProperty, value);}
}
private static void OnSetTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
UserControl1 UserControl1Control = d as UserControl1;
UserControl1Control.OnSetTextChanged(e);
}
private void OnSetTextChanged(DependencyPropertyChangedEventArgs e) {
tbTest.Text = e.NewValue.ToString();
}
}
}
XAML
<Window x:Class = "WpfApplication3.MainWindow"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:views = "clr-namespace:WpfApplication3"
Title = "MainWindow" Height = "350" Width = "604">
<Grid>
<views:UserControl1 SetText = "Hellow World" />
</Grid>
</Window>
I don’t understand the "mechanics" of the operation of class methods UserControl1. That is, at what time they are being called, and by whom.
Does the property necessarily need to be static? I don’t understand the role of the static method on loaded
OnSetTextChangedI see that it just creates an object and calls the method that will make the change.– Matheus Saraiva
Yes the property needs to be static. Regarding the method
OnSetTextChanged(), was something I also noticed, it does not need to be overloaded. It is only necessary to declare it with the signaturevoid OnSetTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e), which is the one that corresponds todelegatePropertychangedcallback, and there put the code to execute when the property is changed, in this case,tbTest.Text = e.NewValue.ToString();.– ramaral