依赖属性ListBox

时间:2010-04-19 18:03:38

标签: c# wpf

我想使用依赖项属性,以便我的标签显示在列表框中选择的值。这只是为了更清楚地理解依赖属性的工作。

<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");
        }
    }
}

任何人都可以解释我如何使用依赖属性来伴随它。不知何故,我对Dependency Property概念感到困惑,我只想看到一个有效的例子。

2 个答案:

答案 0 :(得分:1)

您需要让ListBox“选择”当前文本:

<StackPanel>
    <!-- Add selected item binding -->
    <ListBox 
         x:Name="lbColor" Width="248" Height="56" 
         ItemsSource="{Binding TestColor}"
         SelectedItem="{Binding Test}"
    />

    <StackPanel>
        <!-- No need for elementname - just use Test on the DataContext -->
        <Label Content="{Binding Path=Test}" />
    </StackPanel>
</StackPanel>

答案 1 :(得分:1)

我喜欢将Data Binding视为老大哥。绑定系统将自己设置为观察其所有已注册的绑定,并且当出现正确的标准时(例如,FocusLost或PropertyChanged),绑定系统将源值复制到目标。对于TwoWay或OneWayToSource绑定,如果正确的标准发生,绑定系统甚至会从目标复制到源。

目标必须是DependencyProperty,因为这是一种特殊的属性,它知道如何依赖其他值。 XAML {Binding}正在做什么是创建一个新的BindingExpression,然后调用BindingOperations.SetBinding,它将绑定系统注册到特定的BindingExpression,因此它知道如何观察和执行更新。

这样做的好处是目标和源都不需要负责编写代码来明确更新另一个。如果我有代码知道如何提供颜色列表,为什么我应该关心颜色如何表示给用户?因为绑定系统负责绑定,所以如果使用我的Colors的目标是列表框,树视图或任何其他知道如何处理项目列表的对象,对我来说无关紧要。我可以专注于我关心的事情(我正在公开的公共界面),并且不必关心将该界面粘合到其他东西上的混乱细节。

相关问题