c# - 依赖属性列表框

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

任何人都可以向我解释如何使用依赖属性来完成此任务吗?不知何故,我对依赖属性概念感到非常困惑,我只是想看看一个有效的示例。

最佳答案

您需要让列表框“选择”当前文本:

<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>

关于c# - 依赖属性列表框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2669716/

相关文章:

c# - 如何在不将该颜色应用于每个子控件的情况下更改 GroupBox 的 ForeColor?

c# - HDF5 示例代码

javascript - 返回带撇号的 JsonResult

c# - 如何删除字符串上的重音符号?

c# - 如何在 NUnit 测试中为 WPF 文本框调用 setter

c# - CollectionView 与 WPF(或类似的东西)

c# - 如何为子级TreeView节点设置父级值

c# - Azure Key Vault .NET Core 3.1 Web API 无法访问 secret

c# - WPF/Prism : What is a UNITY Container?

c# - System.WIndows.Application 静态成员是线程安全的吗?