/*by Jiangong SUN*/
XAML: eXtensible Application Markup Language
Dependency property represents a property that can be set through methods such as, styling, data binding, animation, and inheritance.
Dependency properties are the workhorse of WPF. This infrastructure provides for many of WPF's features, such as data binding, animations, and visual inheritance. In fact, most of the various element properties are Dependency Properties.
Here is main window: MainWindow.xaml
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1" <!--local application namespace-->
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<local:SimpleControl x:Name="_simple" /> <!--use a wpf user control named "SimpleControl"-->
<TextBlock Text="{Binding YearPublished, ElementName=_simple}" FontSize="30" /> <!--YearPublished property is binding-->
<Button Content="Change Value" FontSize="20" Click="OnChangeValue" /> <!--When user click on the button, it will call the event handler "OnChangeValue"-->
</StackPanel>
</Window>
Code behind : MainWindow.xaml.cs
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void OnChangeValue(object sender, RoutedEventArgs e)
{
_simple.YearPublished++; //property YearPublished's value increment by 1 in user control SimpleControl's instance
}
}
}
SimpleControl.xaml.cs
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for SimpleControl.xaml
/// </summary>
public partial class SimpleControl : UserControl
{
public SimpleControl()
{
InitializeComponent();
}
//propdp
public int YearPublished
{
get { return (int)GetValue(YearPublishedProperty); }
set { SetValue(YearPublishedProperty, value); }
}
// Using a DependencyProperty as the backing store for YearPublished. This enables animation, styling, binding, etc...
public static readonly DependencyProperty YearPublishedProperty =
DependencyProperty.Register("YearPublished", typeof(int), typeof(SimpleControl), new UIPropertyMetadata(2000, OnValueChanged));
private static void OnValueChanged(DependencyObject obj,DependencyPropertyChangedEventArgs e)
{
// do something when property changes
}
}
}
reference:
http://www.wpftutorial.net/dependencyproperties.html