我对使用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。为此目的,可以为ObservableCollection替换List。
所有其余部分应该在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;
}
}
答案 0 :(得分:1)
您的源是数据上下文,因此您不会将源设置为布尔本身,而是将Source设置为布尔所属的类/元素,就像您已经完成的那样。 Path将是myBoolean或List [5]。
如果布尔值在当前类中,则可以执行
Binding binding = new Binding()
{
Source = this,
Path = new PropertyPath("myBoolean"),
Mode = BindingMode.TwoWay
};
myButton.SetBinding(dp, binding);
您到底想要通过绑定到列表项来实现什么?如果您的列表发生更改,那么您不希望绑定到特定索引,但您可以绑定到所选项目。通过绑定到特定列表项,提供有关您需要实现的更多信息。
Binding binding = new Binding()
{
Source = List,
Path = new PropertyPath("SelectedItem"),
Mode = BindingMode.TwoWay
};
myButton.SetBinding(dp, binding);