From the book WPF 4 Unleashed:
Although the source property can be any .NET property on any .NET
object, the same is not true for the data-binding target. The target
property must be a dependency property. Also note that the source
member must be a real (and public) property, not just a simple field.
However, here’s a counter example to the claim that the source must be a property. This program binds a Label and a ListBox to a normal field of type ObservableCollection<int>.
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}"/>
<ListBox ItemsSource="{Binding Source={StaticResource ints}}"/>
</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()
{
Resources.Add("ints", ints = new ObservableCollection<int>());
InitializeComponent();
}
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);
}
}
}
So what’s the official word on what qualifies as a data binding source? Should we only bind to properties? Or are fields technically allowed as well?
No, this doesn’t bind to the field esplicitly, it binds to the field, by using a
static resource:You can define a static resource whatever you want (basically) and bind to it. If you want to bind directly to your class, you need to use
propertiesas documentation suggests.