Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding an ObservableCollection.Count to Label with WPF

I have a simple Label that should include the bound .Count value of a Property of an ObservableCollection.

The thing is, that the result is always 0 (zero). The same Property is bound to a DataGrid, which works perfectly and even updates if something has changed in the Collection.

What am I doing wrong here?

Here is my code:

<Label ContentStringFormat="Members: {0}">
    <Label.Content>
        <Binding Path="MembersList.Count" Mode="OneWay" UpdateSourceTrigger="Default" />
    </Label.Content>
</Label>

The Property looks like:

public static ObservableCollection<Mitglied> MembersList { get; set; }
like image 446
Pascal Avatar asked Nov 13 '22 00:11

Pascal


1 Answers

I can only assume you've not actually added any items to the collection. If you think you are, you'll have to give us a more complete repro.

This works perfectly for me:

MainWindow.xaml

<Window x:Class="SO18124125.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <Button x:Name="addButton">Add</Button>
        <Label>
            <Label.Content>
                <Binding Path="Items.Count" Mode="OneWay" UpdateSourceTrigger="Default"/>
            </Label.Content>
        </Label>
    </StackPanel>
</Window>

MainWindow.xaml.cs

namespace SO18124125
{
    using System.Collections.ObjectModel;
    using System.Windows;

    public partial class MainWindow : Window
    {
        private static readonly ObservableCollection<string> items = new ObservableCollection<string>();

        public MainWindow()
        {
            InitializeComponent();

            this.DataContext = this;

            this.addButton.Click += delegate
            {
                items.Add("foo");
            };
        }

        public static ObservableCollection<string> Items
        {
            get { return items; }
        }
    }
}

BTW, this is far more succinct:

<Label Content="{Binding Items.Count}" ContentStringFormat="Members: {0}"/>
like image 189
Kent Boogaart Avatar answered Nov 15 '22 12:11

Kent Boogaart