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

标签 c# wpf xaml data-binding

摘自《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和一个 ListBoxObservableCollection<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/

相关文章:

c# - 使用等于。 GetHashCode 不是

c# - x64 中的 Visual Studio 设计器不起作用

c# - 如何测试 API

应用程序中的 C# WPF 多个面板 - 如何做到这一点

c# - MVVM:自定义 devexpress propertyGridControl

c# - ListBox 不显示绑定(bind)数据

c# - 在 Entity Framework 中将数据从一个提供者实时传输到另一个提供者

c# - 指定(或不指定)键时的模板加载行为不同

WPF ListBox 在使用 ICommand 删除后选择下一项

C# WPF 为列表中的每个对象动态创建一个 GUI 元素