我想将 Xamarin.Forms.Button
作为 CommandParameter
传递给我的 ViewModel。我知道如何从后面的代码中实现这一点,例如...
XAML (为简洁起见省略了大部分属性)
<Button x:Name="myButton"
Text="My Button"
Command="{Binding ButtonClickCommand}"/>
XAML.cs
public partial class MyTestPage
{
public MyTestPage()
{
InitializeComponent();
myButton.CommandParameter = myButton;
}
}
View 模型
public class MyViewModel : ViewModelBase
{
public MyViewModel()
{
ButtonClickCommand = new Command(
(parameter) =>
{
var view = parameter as Xamarin.Forms.Button;
if (view != null)
{
// Do Stuff
}
});
}
public ICommand ButtonClickCommand { get; private set; }
}
...但是是否可以在 XAML 本身中声明 CommandParameter
?或者换句话说,将参数设置为按钮本身的绑定(bind)语法是什么?
<Button x:Name="myButton"
Text="My Button"
Command="{Binding ButtonClickCommand}"
CommandParameter="{[WHAT WOULD GO HERE]}"/>
顺便说一句,我已经尝试过 CommandParameter="{Binding RelativeSource={RelativeSource Self}}"
但没有用。
谢谢,
最佳答案
Xamarin.Forms
有一个引用标记扩展,可以做到这一点:
<Button x:Name="myButton"
Text="My Button"
Command="{Binding ButtonClickCommand}"
CommandParameter="{x:Reference myButton}"/>
不过,这是我第一次看到这种需求,您可能可以更好地将 View 与 View 模型分开,并通过使用更清晰的模式或不共享命令来解决此问题跨按钮。
关于c# - 如何在 Xamarin.Forms 页面中将按钮作为 CommandParameter 从 XAML 传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25912091/