Xamarin Forms绑定按钮命令到父BindingContext

Tom*_*asz 9 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>
Run Code Online (Sandbox Code Playgroud)

但我想将命令执行移动到我的userControl绑定上下文.

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

Command={Binding ElementName=myUserControl, Path=DataContext.CategorySelectedCommand}
Run Code Online (Sandbox Code Playgroud)

但它没有ElementName属性.

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

BindingContext="{x:Reference myUserControl}"
Run Code Online (Sandbox Code Playgroud)

但后来我无法将Text属性绑定到我的按钮文本.

我该怎么做?

Kru*_*lur 14

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

Command="{Binding CategorySelectedCommand, Source={x:Static me:SomeStaticClass.YourUserControl}}"
Run Code Online (Sandbox Code Playgroud)

要么

Command="{Binding CategorySelectedCommand, Source={DynamicResource yourUserControlKey}}"
Run Code Online (Sandbox Code Playgroud)

要么

Command="{Binding CategorySelectedCommand, Source={x:Reference myUserControl}}"
Run Code Online (Sandbox Code Playgroud)

这是一个完整的例子.一个常见的问题是在调用之后不实现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>
Run Code Online (Sandbox Code Playgroud)

代码背后

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

    public string TextProp
    {
        get;
        set;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这似乎只有在我的控件是ContentView等的子项时才有效.如果我使用DataTemplate它不起作用 (2认同)