Reputation: 1319
i'm pretty new in wpf and i'm having troubles with a simple ListBox
binding.
This is the case, i have two clases
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);
}
}
And i'm trying to bind it in 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>
And in the code behind
ChildCollection childs = null;
public MainWindow()
{
childs = new ChildCollection();
InitializeComponent();
DataContext = childs;
}
I try to bind the Count
property to a simple TextBlock
and that is showing the Count
but not updating with ChildCollection
object
How shoud i bind it?
Thanks!
Upvotes: 0
Views: 281
Reputation: 128077
The problem is that you explicitly add a ListBoxItem
to the ListBox.
You probably wanted to define the ItemTemplate
instead:
<ListBox ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
You should also consider using an ObservableCollection instead of creating your own collection class:
private readonly ObservableCollection<Child> children = new ObservableCollection<Child>();
public MainWindow()
{
InitializeComponent();
DataContext = children;
}
Upvotes: 2
Reputation: 455
I think the problem is in iappropriate definition of the cobservable collection. Anyway for the learning scenario try to use the standard predefined System.ObservableCollection<> instead. The collection also have to be initialized (not nbe null) in that little experiment...
So in your case, please try as the follows:
ObservablledCollection<Child> childs = new ObservableCollection<Child>;
public MainWindow()
{
InitializeComponent();
DataContext = childs;
}
Upvotes: 0