在本書Visual C# 2010 Recipes: A Problem-Solution Approach中,有一個演示依賴項屬性功能的示例。該示例描述了一個UserControl,它具有兩個屬性TextFontWeight和TextContent,它們分別依附於它們的依賴項屬性TextFontWeightProperty和TextContentProperty。有關依賴項屬性示例的問題
的XAML代碼後面去如下
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
{
/// <summary>
/// Interaction logic for TestDpControl.xaml
/// </summary>
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);
}
}
}}
我無法理解有什麼好處呢依賴屬性提供了此方案。在這種情況下,返回FontWeights.Bold
爲TextFontWeight
和"Default Value"
爲TextContent
的簡單獲得者是否就夠了?如果有人能夠說明這個特定例子中的依賴屬性的權力,或者在這種情況下它的使用是否謹慎,那將是非常好的。
由於
感謝您的所有澄清。這很有幫助。 – 2010-08-10 18:32:49