UserControl 中的 ItemsSource 绑定不起作用

ItemsSource Binding in UserControl doens't work

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

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 的代码隐藏

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 中的列表时,没问题。所以故障必须在其他地方。 希望你能帮上忙!

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

 DataContext = this;

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

谈到 DependencyProperties:public SolidColorBrush Color { get; set; } 不遵循要求的模式,必须使用 GetValue / SetValue 方法实施