UserControl上的XAML绑定

时间:2015-03-05 00:58:54

标签: xamarin.ios xamarin xamarin.forms

我目前有一个用户控件

<?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中我尝试了

以及其他一些变种但却无法发挥作用。

1 个答案:

答案 0 :(得分:0)

试试这个:

public static readonly BindableProperty ListSourceProperty =
   BindableProperty.Create<MultiSelect, ObservableCollection<ListItem>>(p => p.ListSource, new ObservableCollection<ListItem>(), BindingMode.Default, null, (bindable, oldVal,newVal)=>{ (bindable as MultiSelect).LisstSource = newVal;});
相关问题