【问题标题】:ItemsSource Binding in UserControl doens't work [duplicate]UserControl 中的 ItemsSource 绑定不起作用[重复]
【发布时间】:2020-06-02 12:34:57
【问题描述】:

我目前正在测试用户控件,因此创建了这个小应用程序。

Main.xaml

<Grid>
<control:CustomInterfaceGrid Color="Green" Height="400" CustomItemsSource="{Binding Packages}"></control:CustomInterfaceGrid>
</Grid>

UserControl.xaml

<UserControl x:Class="App.Custom.CustomInterfaceGrid"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="App.Custom"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800"
             x:Name="SourceElement"
             >
        <Grid>
        <ListBox x:Name="listView" Background="{Binding Color, ElementName=SourceElement}" ItemsSource="{Binding CustomItemsSource, ElementName=SourceElement}"></ListBox>
    </Grid>
</UserControl>

来自 UserControl 的 CodeBehind

public partial class CustomInterfaceGrid : UserControl, INotifyPropertyChanged
  {

     public CustomInterfaceGrid()
    {
      InitializeComponent();
      DataContext = this;
     }

    public static readonly DependencyProperty ColorProperty =

    DependencyProperty.Register("Color", typeof(SolidColorBrush), typeof(CustomInterfaceGrid));


    public SolidColorBrush Color
    {
      get; set;
    }


    public static readonly DependencyProperty CustomItemsSourceProperty =

    DependencyProperty.Register("CustomItemsSource", typeof(IEnumerable<Object>), typeof(CustomInterfaceGrid));

    public IEnumerable<Object> CustomItemsSource
    {
      get
      {
        return GetValue(CustomItemsSourceProperty) as IEnumerable<Object>;
      }
      set {
        SetValue(CustomItemsSourceProperty, value);
        OnPropertyChanged();
      }
    }
    public event PropertyChangedEventHandler PropertyChanged;


    private void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
      if (PropertyChanged != null)
      {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
      }
    }

  }

问题是当我在 Main 中设置它时颜色会发生变化,但它不会显示列表中的包。 当我将包直接绑定到 Main.xaml 中的列表时,没关系。所以故障必须在其他地方。 希望你能帮忙!

【问题讨论】:

    标签: c# wpf xaml binding itemssource


    【解决方案1】:

    导致绑定错误的主要错误是不必要的设置DataContext。从构造函数中删除这一行:

     DataContext = this;
    

    没有必要为同样是 DependencyObject 的 UserControl 实现 INotifyPropertyChanged。 DependencyProperties 具有通知更改的内部机制。删除OnPropertyChanged - 声明和所有用法。

    说到 DependencyProperties:public SolidColorBrush Color { get; set; } 不符合要求的模式,必须使用 GetValue / SetValue 方法实现

    【讨论】:

    • 谢谢 Ash,我完全被那个错误蒙蔽了双眼。它现在可以工作了!
    猜你喜欢
    • 2015-05-23
    • 1970-01-01
    • 1970-01-01
    • 2015-11-16
    • 1970-01-01
    • 2014-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多