9

我正在编写 Xamarin 应用程序,我发现 WPF 之间的差异是我无法跨越的。

我正在使用 Xamarin Forms Labs 来获得中继器控制。

我有一个Repeater,它重复DataTemplate:

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

但我想将命令执行移至我的 userControl 绑定上下文。

通常使用 WPF 它看起来像:

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

但它没有 ElementName 属性。

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

BindingContext="{x:Reference myUserControl}"

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

我该怎么做?

4

1 回答 1

14

您可以使用该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;
    }
}
于 2015-04-15T14:36:08.047 回答