【发布时间】:2010-04-19 18:03:38
【问题描述】:
我想使用依赖属性,以便我的标签显示在列表框中选择的值。这只是为了更清楚地了解依赖属性的工作原理。
<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");
}
}
}
谁能向我解释我将如何使用依赖属性来完成此任务?不知何故,我对依赖属性的概念感到非常困惑,我只是想看看一个可行的例子。
【问题讨论】:
-
关于您使用依赖属性完成的工作,请看这里:stackoverflow.com/questions/1723756/why-dependency-properties/…
-
我明白有很多例子展示了 DP 和与为什么使用它相关的文档,但我希望看到一些有用的东西,让我了解 DP 在什么步骤中所做的事情.就像它是如何调用的一样,在什么时候设置值以及正在设置的值是什么等等......