0

我有绑定问题:查看我的代码

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

在后面的代码中,我声明了 ocOpenInvoices ObservableCollection:

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

在我的 Window Loadded 事件中:

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

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

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

请你能帮忙告诉我我的问题是什么?我在这里想念什么?提前致谢。

4

2 回答 2

5

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

代替

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 可以解决您的问题。

于 2014-04-06T14:24:40.610 回答
1

确保初始化您的ObservableCollectioninsideWindow's constructorWindow loaded event.

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

如果您在其他地方初始化它,而不是确保实现INotifyPropertyChanged和 raise PropertyChanged

于 2014-04-06T16:40:49.640 回答