如果您希望此成员可通过 Winform 或 WPF 进行数据绑定,我相信您需要将其声明为属性。我大约 95% 的肯定数据绑定需要一个属性(getter/setting 语法)。我有一个小型 wpf 解决方案来演示这一点,但我看不到在此处附加它的方法。
这是代码:(使用 VS 2008 SP1 构建,针对 .net 3.5 - 我使用了 WPF 项目)。
WPF项目中有2个项目,主窗口(window1),以及我们正在测试的对象(DataObject)
窗口上有一个标签,它数据绑定到数据对象实例中的 Name 属性。如果将 Name 属性转换为字段(删除 getter/setter),数据绑定将停止工作。
Window1.xaml:
<Window x:Class="WpfDatabinding.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<Label Name ="Label1" Height="28" Margin="12,24,37,0" VerticalAlignment="Top" Content="{Binding Name}"></Label>
</Grid>
Window1.xaml.cs
using System;
using System.Windows;
namespace WpfDatabinding
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
private DataObject ADataObject;
public Window1()
{
InitializeComponent();
this.ADataObject = new DataObject();
this.ADataObject.Name = "Hello!";
this.DataContext = this.ADataObject;
}
}
}
namespace WpfDatabinding
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
private DataObject ADataObject;
public Window1()
{
InitializeComponent();
this.ADataObject = new DataObject();
this.ADataObject.Name = "Hello!";
this.DataContext = this.ADataObject;
}
}
}
DataObject.cs:
namespace WpfDatabinding
{
public class DataObject
{
// convert this to a field, and databinding will stop working
public string Name
{
get;
set;
}
}
}