加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – Xamarin Forms绑定按钮命令到父BindingContext

发布时间:2020-12-15 08:02:02 所属栏目:百科 来源:网络整理
导读:我正在写Xamarin应用程序,我发现 WPF之间的区别,我无法跨越. 我正在使用Xamarin Forms Labs来控制Repeater. 我有一个Repeater,重复DataTemplate: DataTemplate Button Text="{Binding Text}" Command="{Binding CategorySelectedCommand}" //DataTemplate
我正在写Xamarin应用程序,我发现 WPF之间的区别,我无法跨越.

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

我有一个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属性绑定到我的按钮文本.

我该怎么做?

解决方法

您可以使用Source属性指定将使用的绑定的源,而不是当前的BindingContext.然后文本可以来自页面的绑定上下文和来自其他地方的命令.
Command="{Binding CategorySelectedCommand,Source={x:Static me:SomeStaticClass.YourUserControl}}"

要么

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

要么

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读