[英]How to bind class that inherit from collection wpf
我是WPF的新手,我在使用簡單的ListBox
綁定時遇到了麻煩。
是這種情況,我有兩個說法
public class Child, ImplementedPropertyChanged
{
private string _name;
public string Name
{
get => _name;
set
{
_name = value;
OnPropertyChanged();
}
}
}
public class ChildCollection : IObservableCollection<Child>
{
new public void Add(Child child)
{
//some logic
base.Add(child);
}
}
我正在嘗試將其綁定到XAML
<Window x:Class="GeneradorDeCarpetaPlanos.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:GeneradorDeCarpetaPlanos"
xmlns:VM="clr-namespace:GeneradorDeCarpetaPlanos.ViewModel"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.DataContext>
<VM:ChildCollection></VM:ChildCollection>
</Window.DataContext>
<StackPanel>
<ListBox ItemsSource="{Binding}">
<ListBoxItem>
<TextBlock Text="{Binding Path=Name}"></TextBlock>
</ListBoxItem>
</ListBox>
</StackPanel>
</Window>
並在后面的代碼中
ChildCollection childs = null;
public MainWindow()
{
childs = new ChildCollection();
InitializeComponent();
DataContext = childs;
}
我嘗試將Count
屬性綁定到一個簡單的TextBlock
,這顯示了Count
但未使用ChildCollection
對象更新
我應該如何綁定它?
謝謝!
問題是您將ListBoxItem
顯式添加到ListBox。
您可能想改為定義ItemTemplate
:
<ListBox ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
您還應該考慮使用ObservableCollection而不是創建自己的集合類:
private readonly ObservableCollection<Child> children = new ObservableCollection<Child>();
public MainWindow()
{
InitializeComponent();
DataContext = children;
}
我認為問題出在可可收集的不恰當定義中。 無論如何,對於學習場景,請嘗試使用標准的預定義System.ObservableCollection <>。 在那個小實驗中,還必須初始化集合(不是nbe null)。
因此,根據您的情況,請嘗試以下操作:
ObservablledCollection<Child> childs = new ObservableCollection<Child>;
public MainWindow()
{
InitializeComponent();
DataContext = childs;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.