【问题标题】:WPF ItemsControl binding issueWPF ItemsControl 绑定问题
【发布时间】:2014-04-06 10:53:03
【问题描述】:

我遇到了绑定问题:查看我的代码

这是 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 但它仍然没有响应。

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

【问题讨论】:

  • 您何时创建 ocOpenInvoices? InitializeComponent(); 之前或之后的绑定可以在您创建之前完成。所以它绑定在 NULL 上。
  • @JeroenvanLangen 我在 Window Loaded 中创建它
  • 这一切似乎都有效(至少在一个使用单个 Window 类的小例子中),你能在一个小例子项目中重现问题吗?

标签: c# wpf xaml observablecollection itemsource


【解决方案1】:

尝试将您的 observable 集合抽象为私有变量 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 可以解决您的问题。

【讨论】:

【解决方案2】:

确保在Window's constructorWindow loaded event 中初始化ObservableCollection

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

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

【讨论】:

    猜你喜欢
    • 2011-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    • 2016-06-04
    • 1970-01-01
    相关资源
    最近更新 更多