Search code examples
c#wpfxamlobservablecollectionitemsource

WPF ItemsControl binding issue


I have problem with Binding: see my code

This is Xaml code:

<ItemsControl x:Name="lbOpenInvoices" ItemsSource="{Binding Path=ocOpenInvoices}">
<ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
        <UniformGrid Columns="3" VerticalAlignment="Top" />
    </ItemsPanelTemplate>
</ItemsControl.ItemsPanel>

<ItemsControl.ItemTemplate>
    <DataTemplate>
        <Button x:Name="btnOpenInvoice" Click="btnOpenInvoice_Click" Style="{StaticResource OpenInvoicesButton}">
            <StackPanel Orientation="Vertical">
                <TextBlock Text="{Binding Converter={StaticResource InvoiceNoTableNo}}"/>
                <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
                    <TextBlock Text="{Binding Converter={StaticResource InvoiceNoInvoiceId}}"/>
                    <TextBlock Text="{Binding TotalAmount}" FontSize="14" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                </StackPanel>
                <TextBlock Text="{Binding Converter={StaticResource InvoiceDateTime}}"/>
            </StackPanel>
        </Button>
    </DataTemplate>
</ItemsControl.ItemTemplate>

In Code behind I have declared the ocOpenInvoices ObservableCollection:

        public ObservableCollection<Invoice> ocOpenInvoices { get; set; }

And In my Window Loadded event:

        void SaleWindow_Loaded(object sender, RoutedEventArgs e)
        {
          this.DataContext = this;
        }

But It driving me Crazy because the ItemControl does not respond to ocOpenInvoices ObservableCollection.

When I give it the ItemsSource from codebehind it works :(, I have tried to give it the ElementName but it still not respond.

Please can you help and tell me what's my problem? what I miss here? Thanks in advance.


Solution

  • Try abstracting your observable collection over a private variable a private, it will work.

    Replace

    public ObservableCollection<Invoice> ocOpenInvoices { get; set; }
    

    with

    private ObservableCollection<Invoice> _ocOpenInvoices;
    public ObservableCollection<Invoice> ocOpenInvoices
    { 
      get { return _ocOpenInvoices ; } 
      set { _ocOpenInvoices = value; OnPropertyChange("ocOpenInvoices"); }
    }
    

    Please ignore this OnPropertyChange, if you have already implemented INotifyPropertyChanged in your own way, otherwise, it would be INotifyPropertyChanged that can solve your issue.