我在数据绑定项中遇到问题,从集合到网格内容视图。
请查看以下代码。这仅用于表示,它是完整逻辑的一部分。
查看模型类
public class ViewModel : INotifyPropertyChanged
{
private ObservableCollection<ChildViewModel> myProperty;
public ObservableCollection<ChildViewModel> MyProperty
{
get
{
return myProperty;
}
set
{
if (myProperty != value)
{
myProperty = value;
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs("MyProperty"));
}
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
public class ChildViewModel : INotifyPropertyChanged
{
private string prop1;
private string prop2;
public string Prop1
{
get
{
return prop1;
}
set
{
if (prop1 != value)
{
prop1 = value;
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs("Prop1"));
}
}
}
}
public string Prop2
{
get
{
return prop2;
}
set
{
if (prop2 != value)
{
prop2 = value;
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs("Prop2"));
}
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
使用View Model Class
ChildViewModel objChildViewModel1 = new ChildViewModel { Prop1 = "Prop1", Prop2 = "Prop2" };
ChildViewModel objChildViewModel2 = new ChildViewModel { Prop1 = "Prop1", Prop2 = "Prop2" };
ViewModel obj = new ViewModel
{
MyProperty = new ObservableCollection<ChildViewModel> { objChildViewModel1,objChildViewModel2}
};
//set binding context
this.BindingContext = obj;
var grid = new Grid();
grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
var Label1 = new Label { };
//how to databind obj.MyProperty[0].Prop1 to Label1 ???
var Label2 = new Label { };
//how to databind obj.MyProperty[1].Prop1 to Label2 ???
var Entry1 = new Entry { };
//how to databind obj.MyProperty[0].Prop2 to Entry1 ???
var Entry2 = new Entry { };
//how to databind obj.MyProperty[1].Prop2 to Entry2 ???
grid.Children.Add(Label1, 0, 0);
grid.Children.Add(Entry1, 0, 1);
grid.Children.Add(Label2, 1, 0);
grid.Children.Add(Entry2, 1, 1);
正如我在代码中所示,我想从LabelModel类的对象中为Label1,Label2,Entry1和Entry2进行数据绑定。我知道基本的数据绑定,其中只有绑定属性与名称以xamarin形式查看/控制,但在这里我无法绑定它。请帮助我。
答案 0 :(得分:0)
grid.BindingContext=obj;
Label1.SetBinding (Label.TextProperty, "MyProperty[0].Prop1");
Label2.SetBinding (Label.TextProperty, "MyProperty[1].Prop1");
Entry1.SetBinding (Entry.TextProperty, "MyProperty[0].Prop2");
Entry2.SetBinding (Entry.TextProperty, "MyProperty[1].Prop2");