WPF ItemsControl绑定问题

时间:2014-04-06 10:53:04

标签: c# wpf xaml observablecollection itemsource

我遇到绑定问题:请参阅我的代码

这是Xaml代码:

<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>

在Code背后,我已经声明了ocOpenInvoices ObservableCollection:

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

在我的Window加载事件中:

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

但它让我疯狂,因为ItemControl不响应ocOpenInvoices ObservableCollection。

当我从代码隐藏中给它ItemsSource时,它可以工作:(,我试图给它ElementName,但它仍然没有响应。

请帮助,告诉我我的问题是什么?我想念的是什么? 提前谢谢。

2 个答案:

答案 0 :(得分:5)

尝试通过私有变量将您的可观察集合抽象为私有变量,它将起作用。

替换

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

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

如果您已经以自己的方式实现了INotifyPropertyChanged,请忽略此OnPropertyChange,否则,它将是可以解决您的问题的INotifyPropertyChanged。

答案 1 :(得分:1)

确保在ObservableCollectionWindow's constructor内初始化Window loaded event

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

如果您在其他地方初始化它,请确保实施INotifyPropertyChanged并提升PropertyChanged