Xamarin Forms 绑定按钮命令到父 BindingContext [英] Xamarin Forms binding button Command to parent BindingContext

查看:24
本文介绍了Xamarin Forms 绑定按钮命令到父 BindingContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writing Xamarin application and I found difference between WPF which I cannot cross.

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

I'm using Xamarin Forms Labs to get Repeater control.

我有一个重复数据模板的中继器:

I have a Repeater, which repeats DataTemplate:

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

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

But i would like to move command execution to my userControl Binding Context.

通常使用 WPF 它看起来像:

Normally with WPF it would look like:

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

但它没有 ElementName 属性.

But it does not have ElementName property.

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

I have found that I could set BindingContext of my button like this:

BindingContext="{x:Reference myUserControl}"

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

But then I cannot bind Text property to my button's text.

我该怎么做?

推荐答案

您可以使用 Source 属性来指定将用于代替当前 BindingContext<的绑定的源/代码>.然后文本可以来自页面的绑定上下文和来自其他地方的命令.

You can use the Source property to specify a source for the binding that will be used instead of the current BindingContext. Then the text can come from the page's binding context and the command from somewhere else.

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

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

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

这是一个完整的例子.一个常见的问题是没有实现 INotifyPropertyChanged 并在调用 InitializeComponent() 之后设置属性.

Here's a complete example. A common problem is to not implement INotifyPropertyChanged and set the property after the call to 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;
    }
}

这篇关于Xamarin Forms 绑定按钮命令到父 BindingContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆