【问题标题】:Xamarin Forms binding button Command to parent BindingContextXamarin Forms 绑定按钮命令到父 BindingContext
【发布时间】:2015-06-21 03:59:57
【问题描述】:

我正在编写 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 属性绑定到按钮的文本。

我应该怎么做?

【问题讨论】:

  • 您找到解决方案了吗? Source 似乎不适用于 DataTemplate。这也太可惜了,很难做真正的 MVVM。
  • 没关系。我落后于更新。这似乎现在起作用了。

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


【解决方案1】:

您可以使用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;
    }
}

【讨论】:

  • 我有一个 ContentPage 和 x:Name wireframe。在此页面的 ViewModel 中,我有属性 MainText。然后在 DataTemplate 我有标签:&lt;Label Text="{Binding Source={x:Reference wireframe}, Path=MainText}"&gt;&lt;/Label&gt; 它不起作用。我也试过Path=BindingContext.MainText。没有成功
  • 该属性是否公开?
  • 这似乎只在我的控件是 ContentView 等的子控件时才有效。如果我使用 DataTemplate 它不起作用
猜你喜欢
  • 2019-07-30
  • 2019-05-11
  • 1970-01-01
  • 2020-03-06
  • 2017-08-18
  • 2019-12-25
  • 2017-04-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多