【发布时间】:2015-03-14 08:33:10
【问题描述】:
我目前有一个用户控件
<?xml version="1.0" encoding="utf-8" ?>
<StackLayout xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Mobile.Control.MultiSelect">
<ListView ItemsSource="{Binding ListSource}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<ContentView Padding="10">
<StackLayout Orientation="Horizontal">
<Label Text="{Binding Name}" HorizontalOptions="Center" TextColor="White" />
</StackLayout>
</ContentView>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
在我后面的代码中
public partial class MultiSelect : StackLayout
{
public MultiSelect()
{
InitializeComponent();
BindingContext = this;
}
public static readonly BindableProperty ListSourceProperty =
BindableProperty.Create<MultiSelect, ObservableCollection<ListItem>>(p => p.ListSource, new ObservableCollection<ListItem>());
public ObservableCollection<ListItem> ListSource
{
get { return (ObservableCollection<ListItem>)GetValue(ListSourceProperty); }
set { SetValue(ListSourceProperty, value); }
}
}
然后在我的 XAML 页面中
<control:MultiSelect x:Name="MyMultiSelect" />
问题是,我如何在 XAML 的 BindingContext 中绑定一些东西 页面到用户控件。
在我的 XAML 页面后面的代码中
MyMultiSelect.ListSource = BindingContext.MyList;
这很好用。但是我不想在我的 XAML 页面后面的代码中包含任何内容,因为它违背了我正在进行的漂亮干净的 MVVM 模式,我的代码在其他方面很好、干净和空。
我尝试过在 XAML 中
还有很多其他变体,但无法正常工作。
【问题讨论】:
-
您是否看到 this link 描述了 Xamarin 表单中自定义控件中的数据绑定?
-
我想通了。大约 2 年后,我创建了自己的博客文章:xamarinhelp.com/xamarin-forms-user-control
标签: xamarin.ios xamarin xamarin.forms