摘自《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.
但是,这里有一个反例,证明源必须是属性。该程序绑定(bind)了Label
和一个 ListBox
到 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);
}
}
}
那么关于数据绑定(bind)源的官方说法是什么?我们应该只绑定(bind)属性吗?或者技术上也允许字段?
最佳答案
不,这不会明确绑定(bind)到字段,而是通过使用静态资源
绑定(bind)到字段:
Binding Source={StaticResource ints //StaticResource !!
您可以定义任何您想要的静态资源(基本上)并绑定(bind)到它。如果您想直接绑定(bind)到您的类,则需要按照文档的建议使用属性
。
关于c# - 关于绑定(bind)到非属性(即字段)的官方说法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10621140/