Xamarin.Forms和ElementName绑定

3
我将尝试将我的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 的子级。 - Tomasz
我不清楚你想做什么。你能给一些上下文来解释你的问题吗?你在UI中想要实现什么目标? - Sten Petrov
不确定是否可以遵循...您是否只需在绑定上下文中拥有一个Parent属性,并在其中调用RemoveCommand呢?像这样:Command="{Binding Parent.RemoveCommand}"?您不想在UI元素上调用命令(这就是x:Reference的作用)。 命令的发送者将是当前元素,因此此处无需使用参数。 - Krumelur
1个回答

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"/>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接