【问题标题】:XAML Binding on UserControlUserControl 上的 XAML 绑定
【发布时间】: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 中

还有很多其他变体,但无法正常工作。

【问题讨论】:

标签: xamarin.ios xamarin xamarin.forms


【解决方案1】:

试试这个:

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;});

【讨论】:

    猜你喜欢
    • 2014-07-02
    • 1970-01-01
    • 2017-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多