I have the following dependency property in my MainWindow class (inherits from WPF’s Window)
public ObservableCollection<ComputerListItem> ActiveComputers
{
get { return (ObservableCollection<ComputerListItem>)this.GetValue(ActiveComputersProperty); }
set { this.SetValue(ActiveComputersProperty, value); }
}
public static readonly DependencyProperty ActiveComputersProperty = DependencyProperty.Register(
"ActiveComputers", typeof(ObservableCollection<ComputerListItem>), typeof(MainWindow), new PropertyMetadata(new ObservableCollection<ComputerListItem>()));
Now I’m trying to give a label the value of ActiveComputers.Count so in my XAML I have this:
<Window x:Class="ComputerManagerV3.MainWindow"
<!-- SNIP -->
DataContext="{Binding RelativeSource={RelativeSource Self}}"
>
<Grid>
<!--SNIP -->
<Label Name="labelActive" Content="{Binding Source=ActiveComputers, Path=Count}" ></Label>
Even in the designer the value the label now shows is 15, strange since the list is initially filled with 13 elements. So I added some tests and no matter how much items there are in the observable collection, the label always shows the value 15 :/. There are also no binding errors shown in the output window so I’m clueless as what to do.
My questions:
- Why is the value of the binding expression always 15?
- How can I write a correct binding so that it always shows the number of items in the
list - Is it possible to prepend some text without writing a value
converter myself?
Your binding’s source is the literal
string“ActiveComputers”, which has 15 characters in it. Thus, you’re displaying the count of characters in the string, and are not connected to the collection at all.Try this: