Skip to main content
 首页 » 编程设计

c#之依赖属性列表框

2024年02月24日28Renyi-Fan

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

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