我想使用依賴項屬性,以便我的標籤顯示在列表框中選擇的值。這只是爲了更清楚地理解依賴屬性的工作。依賴項屬性列表框
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:WPFToolkit="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit"
xmlns:local="clr-namespace:WpfApplication1" x:Name="MyWindow"
Height="200" Width="300" >
<StackPanel>
<ListBox x:Name="lbColor" Width="248" Height="56" ItemsSource="{Binding TestColor}"/>
<StackPanel>
<Label Content="{Binding Path=Test, ElementName=lbColor}" />
</StackPanel>
</StackPanel>
</Window>
代碼背後,
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public ObservableCollection<string> TestColor { get; set; }
public String Test
{
get { return (String)GetValue(TestProperty); }
set { SetValue(TestProperty, value); }
}
// Using a DependencyProperty as the backing store for Title. This enables animation, styling, binding, etc...
public static readonly DependencyProperty TestProperty =
DependencyProperty.Register("Test", typeof(String), typeof(ListBox), new UIPropertyMetadata("Test1"));
public Window1()
{
InitializeComponent();
TestColor = new ObservableCollection<string>();
DataContext = this;
TestColor.Add("Red");
TestColor.Add("Orange");
TestColor.Add("Yellow");
TestColor.Add("Green");
TestColor.Add("Blue");
}
}
}
任何人都可以解釋我這個使用依賴屬性如何將我accompalish。不知何故,我對依賴屬性概念非常困惑,我只是想看到一個可行的例子。
對於你完成使用依賴屬性,看看這裏:http://stackoverflow.com/questions/1723756/why-dependency-properties/1723831#1723831 – 2010-04-19 18:06:38
我明白,有很多例子顯示DP以及與爲什麼要使用它有關的文檔,但我希望看到一些有用的信息,以便讓我瞭解DP在哪一步執行的操作。就像它是如何被調用的,在什麼時候設置了值,什麼是設置的值以及所有.. – developer 2010-04-19 18:20:59