【问题标题】:Xamarin.Forms and binding for ElementNameXamarin.Forms 和 ElementName 的绑定
【发布时间】:2015-09-02 09:18:06
【问题描述】:

我正在尝试将我的 ListView 项绑定到来自我的父 ViewModel 的命令。问题是我想在当前项目中添加 CommandParameter

基本上,在 WPF 中我会做类似的事情

<MyItem Command="{Binding ElementName=parent", Path=DataContext.MyCommand}" CommandParameter="{Binding}"/>

在 Xamarin Forms ElementName 中不起作用,所以方法是使用 BindingContext,但我应该如何使用它(如果我的一个绑定点指向父级,第二个指向自身)?

我试过了

<MyItem Command="{Binding BindingContext.RemoveCommand, Source={x:Reference parent}}" CommandParameter="{Binding }" />

但它不起作用(似乎它没有改变源)。

我知道,普通绑定的一种方法是使用BindingContext="{x:Reference parent}",但在这个例子中它不起作用,因为我需要Self 绑定CommandParameter

我该怎么做?

【问题讨论】:

  • 另外,MyItem 是 DataTemplate 的子项
  • 我不清楚你想做什么。你能给你的问题一些背景吗?您想在 UI 中实现什么目标?
  • 不确定我是否可以关注...您不会在绑定上下文中简单地拥有一个 Parent 属性并调用 RemoveCommand 吗?喜欢:Command="{Binding Parent.RemoveCommand}"?您不想在 UI 元素上调用命令(这就是 x:Reference 的用途)。命令的 sender 将是当前元素,所以这里不需要使用参数。

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


【解决方案1】:

我了解您想在当前节点的父节点上执行命令,但将当前节点作为参数传递。如果是这样的话,你可以这样解决:

这是我们绑定的模型。它有一个Parent 属性并定义了一个ICommand(请注意,所有代码都是C#6,所以你需要XS 或VS2015!):

public class BindingClass
{
    public BindingClass (string title)
    {
        this.TestCommand = new TestCommandImpl (this);
        this.Title = title;
    }

    public string Title { get; }
    public ICommand TestCommand { get; }
    public BindingClass Parent { get; set; }
}

在后面的代码中,设置了绑定上下文:

this.BindingContext = new BindingClass ("Bound Button") {
    Parent = new BindingClass ("Parent")
};

而在XAML中,我们有一个按钮调用父节点的命令,并将当前节点作为参数传递:

<Button
    x:Name="btnTest"
    Text="{Binding Title}"
    Command="{Binding Parent.TestCommand}"
    CommandParameter="{Binding}"
    VerticalOptions="CenterAndExpand"
    HorizontalOptions="CenterAndExpand"/>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-25
    • 2012-10-12
    • 1970-01-01
    • 2010-11-04
    • 2012-07-14
    • 2010-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多