关于绑定到非属性(即字段)的官方说法是什么?

dha*_*ech 2 c# data-binding wpf xaml

从WPF 4 Unleashed一书中可以看出:

虽然source属性可以是任何.NET对象上的任何.NET属性,但数据绑定目标也不是这样.target属性必须是依赖项属性.另请注意,源成员必须是真实(和公共)属性,而不仅仅是简单字段.

但是,这是声明源必须是属性的反例.该程序将a Label和a 绑定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>
Run Code Online (Sandbox Code Playgroud)

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);
        }
    }    
}
Run Code Online (Sandbox Code Playgroud)

那么什么是有资格作为数据绑定源的官方消息呢?我们应该只绑定属性吗?或者技术上也允许使用字段?

Tig*_*ran 5

不,这不会绑定到外地esplicitly,它结合领域,通过使用static resource:

Binding Source={StaticResource ints //StaticResource !!
Run Code Online (Sandbox Code Playgroud)

您可以根据需要(基本上)定义静态资源并绑定到它.如果要直接绑定到类,则需要使用properties文档建议.