In my code-behind I have the following in the class:
public ObservableCollection<int> ints;
Its value is initialized in the constructor:
ints = new ObservableCollection<int>();
I’m then binding a label to ints:
<Label Name="label" Content="{Binding Source={StaticResource ints}, Path=Count}"/>
After running the program, a XamlParseException occurs:
‘Provide value on ‘System.Windows.StaticResourceExtension’ threw an
exception.’ Line number ’12’ and line position ’20’.
I guess there is something wrong with the binding line. Any suggestions?
A complete demonstration program illustrating the issue follows:
XAML:
<Window x:Class="BindingObservableCollectionCountLabel.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">
<DockPanel>
<StackPanel>
<TextBox Name="textBox" Text="10"/>
<Button Name="add" Click="add_Click" Content="Add"/>
<Button Name="del" Click="del_Click" Content="Del"/>
<Label Name="label" Content="{Binding Source={StaticResource ints}, Path=Count}"/>
</StackPanel>
</DockPanel>
</Window>
C#:
using System;
using System.Windows;
using System.Collections.ObjectModel;
namespace BindingObservableCollectionCountLabel
{
public partial class MainWindow : Window
{
public ObservableCollection<int> ints;
public MainWindow()
{
InitializeComponent();
ints = new ObservableCollection<int>();
}
private void add_Click(object sender, RoutedEventArgs e)
{
ints.Add(Convert.ToInt32(textBox.Text));
}
private void del_Click(object sender, RoutedEventArgs e)
{
if (ints.Count > 0) ints.RemoveAt(0);
}
}
}
If having that collection in resources is not a requirement, do the following:
Change binding to
Make
intsa property:public ObservableCollection<int> ints { get; private set; }If you need this collection to be a resource, change you window constructor to
and leave XAML unchanged