我正在尝试将视图模型中的内容绑定到视图。
我正在使用一个代码片段,该片段创建一个自定义StackLayout,我们可以在其中绑定项目。
但是我没有做这个工作,我的UI没有更新。我不确定到底要绑定到“项目”。我目前正在用按钮绑定一个observablecollection,但是它没有显示。
这是自定义堆栈布局:
using Xamarin.Forms;
using System.Collections.Specialized;
using System.ComponentModel;
class CustomStackLayout : StackLayout
{
public static readonly BindableProperty ItemsProperty =
BindableProperty.Create(nameof(Items), typeof(ObservableCollection<View>), typeof(CustomStackLayout), null,
propertyChanged: (b, o, n) =>
{
(n as ObservableCollection<View>).CollectionChanged += (coll, arg) =>
{
switch (arg.Action)
{
case NotifyCollectionChangedAction.Add:
foreach (var v in arg.NewItems)
(b as CustomStackLayout).Children.Add((View)v);
break;
case NotifyCollectionChangedAction.Remove:
foreach (var v in arg.NewItems)
(b as CustomStackLayout).Children.Remove((View)v);
break;
case NotifyCollectionChangedAction.Move:
//Do your stuff
break;
case NotifyCollectionChangedAction.Replace:
//Do your stuff
break;
}
};
});
public ObservableCollection<View> Items
{
get { return (ObservableCollection<View>)GetValue(ItemsProperty); }
set { SetValue(ItemsProperty, value); }
}
}
这就是我收集内容的方式。
public MainPageViewModel()
{
CategoryName = new ObservableCollection<Button>();
}
ObservableCollection<Button> _categoryName;
public ObservableCollection<Button> CategoryName
{
get
{
return this._categoryName;
}
set
{
if (_categoryName != value)
{
this._categoryName = value;
RaisePropertyChanged("CategoryName");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string propName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
然后我在空白处收集新数据:
private async void LoadCategories()
{
var GetCategories = await Data.Categories();
CategoryName = new ObservableCollection<Button>();
foreach (var Category in GetCategories["results"])
{
var CategoryButton = new Button();
CategoryButton.Text = Category["CategoryName"].ToString().ToUpper();
CategoryName.Add(CategoryButton);
}
}
xaml:
<ContentPage x:Name="ParentView">
<ScrollView x:Name = "CategoriesScrollView">
<controls:CustomStackLayout Orientation="Horizontal" Spacing="20" Items = "{Binding BindingContext.CategoryName, Source={x:Reference ParentView}}" />
</ScrollView>
查看:
public MainPage()
{
InitializeComponent();
BindingContext = new MainPageViewModel();
}
答案 0 :(得分:1)
几件事
该课程应该是公开的。...
class BindableStackLayout : StackLayout
{..
到
public class BindableStackLayout : StackLayout
{..
和
<ScrollView x:Name = "CategoriesScrollView">
<controls:CustomStackLayout Orientation="Horizontal" Spacing="20" Items = "{Binding BindingContext.CategoryName, Source={x:Reference ParentView}}" />
</ScrollView>
到
<ScrollView x:Name = "CategoriesScrollView">
<controls:BindableStackLayout Orientation="Horizontal" Spacing="20" Items = "{Binding CategoryName}" />
</ScrollView>
您将类定义为BindableStacklayout,并在Xaml上引用CustomStackLayout。
由于页面的绑定上下文已设置为所需的viewModel,因此无需添加x:refe。
希望可以解决此问题吗?