我有一个关于使用 c# 代码在 WP7 中进行数据绑定的问题。
如果我有自定义课程,一切都很清楚。我将 Source 属性设置为我的类实例,将 Path 属性设置为该类中的一个属性。像这样(并且有效)
Binding binding = new Binding()
{
Source = myclass,
Path = new PropertyPath("myproperty"),
Mode = BindingMode.TwoWay
};
myButton.SetBinding(dp, binding);
现在,我如何绑定简单的结构,例如布尔变量或 List<> 中的单个项目?如果我要写Source = myBoolean
或者Source = List[5]
我应该在 Path 属性中写什么?(请注意,我需要 TwoWay 绑定,因此必须设置 Path 属性)
最终解决方案:
要绑定一个变量,这个变量应该是一个公共属性,并且应该实现 INotifyPropertyChanged。为此,可以将 List 替换为 ObservableCollection。
其余的应该看起来像 nmaait 的答案,整个代码应该是这样的:
public partial class Main : PhoneApplicationPage, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private Boolean _myBoolean { get; set; }
public Boolean myBoolean
{
get { return _myBoolean; }
set { _myBoolean = value; OnPropertyChanged("myBoolean"); }
}
ObservableCollection<Int32> myList { get; set; }
public Main()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(Main_Loaded);
}
protected void OnPropertyChanged(String name)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
void Main_Loaded(object sender, RoutedEventArgs e)
{
myBoolean = false;
myList = new ObservableCollection<int>() { 100, 150, 200, 250 };
Binding binding1 = new Binding()
{
Source = this,
Path = new PropertyPath("myBoolean"),
Mode = BindingMode.TwoWay
};
myButton.SetBinding(Button.IsEnabledProperty, binding1);
Binding binding2 = new Binding()
{
Source = myList,
Path = new PropertyPath("[1]"),
Mode = BindingMode.TwoWay
};
myButton.SetBinding(Button.WidthProperty, binding2);
}
private void changeButton_Click(object sender, RoutedEventArgs e)
{
myList[1] +=50;
myBoolean = !myBoolean;
}
}