Xamarin Forms绑定按钮命令到父BindingContext

时间:2015-04-15 09:05:15

标签: c# xamarin.ios xamarin.forms xamarin.forms.labs

我正在编写Xamarin应用程序,我发现了WPF之间的区别,我无法跨越。

我正在使用Xamarin Forms Labs来控制Repeater。

我有一个Repeater,重复DataTemplate:

<DataTemplate>
  <Button Text="{Binding Text}" Command="{Binding CategorySelectedCommand}"  />
</DataTemplate>

但我想将命令执行移动到我的userControl Binding Context。

通常使用WPF,它看起来像:

Command={Binding ElementName=myUserControl, Path=DataContext.CategorySelectedCommand}

但它没有ElementName属性。

我发现我可以像这样设置我的按钮的BindingContext:

BindingContext="{x:Reference myUserControl}"

但是我无法将Text属性绑定到我的按钮文本。

我该怎么做?

1 个答案:

答案 0 :(得分:13)

您可以使用Source属性指定将使用的绑定的来源,而不是当前的BindingContext。然后,文本可以来自页面的绑定上下文和来自其他地方的命令。

Command="{Binding CategorySelectedCommand, Source={x:Static me:SomeStaticClass.YourUserControl}}"

Command="{Binding CategorySelectedCommand, Source={DynamicResource yourUserControlKey}}"

Command="{Binding CategorySelectedCommand, Source={x:Reference myUserControl}}"

这是一个完整的例子。一个常见问题是,在INotifyPropertyChanged调用后,不实施InitializeComponent()并设置属性

<强> XAML

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="test.MyPage" x:Name="ThePage">
    <Label Text="{Binding TextProp, Source={x:Reference ThePage}" HorizontalOptions="Center" VerticalOptions="CenterAndExpand" />
</ContentPage>

代码

public partial class MyPage : ContentPage
{
    public MyPage ()
    {
        this.TextProp = "Some Text";
        InitializeComponent ();
    }

    public string TextProp
    {
        get;
        set;
    }
}