WPF 项控件绑定问题

本文关键字:问题 绑定 控件 WPF | 更新日期: 2023-09-27 17:56:50

我在绑定方面有问题:请参阅我的代码

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

在代码隐藏中,我声明了ocOpenInvoicesObservableCollection:

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

在我的窗口中,Loadd事件:

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

但它让我发疯,因为 ItemControl 没有响应 ocOpenIninvoice ObservableCollection。

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

请你帮忙告诉我我的问题是什么?我在这里错过了什么?提前谢谢。

WPF 项控件绑定问题

尝试将可观察集合抽象到私有变量上,它会起作用。

取代

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

确保在

Window's constructorWindow loaded event 内初始化ObservableCollection

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

如果要在其他地方初始化它,请确保实现 INotifyPropertyChanged 并引发PropertyChanged