In Visual C # 2010 Recipes: An Approach to Problem Solving , there is an example that demonstrates the power of dependency properties. This example describes a UserControl that has two properties, TextFontWeight and TextContent, that have the dependency properties TextFontWeightProperty and TextContentProperty, respectively.
XAML code is as follows
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 TestWpfApplication
{
public partial class TestDpControl : UserControl
{
public TestDpControl()
{
InitializeComponent();
DataContext = this;
}
public FontWeight TextFontWeight
{
get { return (FontWeight)GetValue(TextFontWeightProperty); }
set { SetValue(TextFontWeightProperty, value); }
}
public string TextContent
{
get { return (string)GetValue(TextContentProperty); }
set { SetValue(TextContentProperty, value); }
}
public static readonly DependencyProperty TextContentProperty =
DependencyProperty.Register(
"TextContent",
typeof(string),
typeof(TestDpControl),
new FrameworkPropertyMetadata(
"Default Value",
FrameworkPropertyMetadataOptions.AffectsArrange
& FrameworkPropertyMetadataOptions.AffectsMeasure
& FrameworkPropertyMetadataOptions.AffectsRender));
public static readonly DependencyProperty TextFontWeightProperty =
DependencyProperty.Register(
"TextFontWeight",
typeof(FontWeight),
typeof(TestDpControl),
new FrameworkPropertyMetadata(FontWeights.Normal,
FrameworkPropertyMetadataOptions.AffectsArrange
& FrameworkPropertyMetadataOptions.AffectsMeasure
& FrameworkPropertyMetadataOptions.AffectsRender,
TextFontWeight_PropertyChanged,
TextFontWeight_CoerceValue));
private static object TextFontWeight_CoerceValue(DependencyObject d, object value)
{
FontWeight fontWeight = (FontWeight)value;
if (fontWeight == FontWeights.Bold || fontWeight == FontWeights.Normal)
{
return fontWeight;
}
return FontWeights.Normal;
}
private static void TextFontWeight_PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
TestDpControl myControl = d as TestDpControl;
if (myControl != null)
{
FontWeight fontWeight = (FontWeight)e.NewValue;
string fontWeightName;
if (fontWeight == FontWeights.Bold)
fontWeightName = "Bold";
else
fontWeightName = "Normal";
myControl.txblFontWeight.Text = string.Format("Font weight set to:{0}.", fontWeightName);
}
}
}}
, . getter, FontWeights.Bold TextFontWeight "Default Value" TextContent? , - Dependency .