Привязка ItemsSource в UserControl не работает

В настоящее время я тестирую 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>

CodeBehind от 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, все в порядке. Значит, вина должна быть в другом. Надеюсь, вы можете помочь!


person boom3x    schedule 18.02.2020    source источник


Ответы (1)


основные ошибки, которые приводят к ошибкам привязки, — это ненужный набор DataContext. удалите эту строку из конструктора:

 DataContext = this;

нет необходимости реализовывать INotifyPropertyChanged для UserControl, который также является DependencyObject. DependencyProperties имеют внутренний механизм для уведомления об изменениях. Удалить OnPropertyChanged - декларацию и все обычаи.

Говоря о DependencyProperties: public SolidColorBrush Color { get; set; } не соответствует требуемому шаблону и должен быть реализован с помощью метода GetValue / SetValue.

person ASh    schedule 18.02.2020
comment
Спасибо, Эш, я был полностью ослеплен этой ошибкой. Теперь это работает! - person boom3x; 18.02.2020