質問

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.

役に立ちましたか?

解決

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.

他のヒント

Make sure you initialize your ObservableCollection within Window's constructor or Window loaded event.

void SaleWindow_Loaded(object sender, RoutedEventArgs e)
{
   ocOpenInvoices = new ObservableCollection<Invoice>();
   this.DataContext = this;
}

If you are initializing it somewhere else than make sure you implement INotifyPropertyChanged and raise PropertyChanged.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top