![](/img/trans.png)
[英]Xamarin Forms - CommandParameter - How to pass custom object via XAML?
[英]How do I pass the Button as CommandParameter from XAML in a Xamarin.Forms Page?
我想將它自己的Command
中的Xamarin.Forms.Button
作為CommandParameter
傳遞給我的 ViewModel。 我知道如何從背后的代碼中實現這一點,例如......
XAML (為簡潔起見省略了大多數屬性)
<Button x:Name="myButton"
Text="My Button"
Command="{Binding ButtonClickCommand}"/>
XAML文件
public partial class MyTestPage
{
public MyTestPage()
{
InitializeComponent();
myButton.CommandParameter = myButton;
}
}
視圖模型
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
嗎? 或者換句話說,將參數設置為按鈕本身的綁定語法是什么?
<Button x:Name="myButton"
Text="My Button"
Command="{Binding ButtonClickCommand}"
CommandParameter="{[WHAT WOULD GO HERE]}"/>
順便說一句,我已經嘗試過CommandParameter="{Binding RelativeSource={RelativeSource Self}}"
並且沒有用。
謝謝,
Xamarin.Forms
有一個 Reference 標記擴展可以做到這一點:
<Button x:Name="myButton"
Text="My Button"
Command="{Binding ButtonClickCommand}"
CommandParameter="{x:Reference myButton}"/>
雖然,這是我第一次看到這種需求,您可能可以更好地將視圖與視圖模型分開,並通過使用更簡潔的模式或不跨按鈕共享命令來解決此問題。
<Button x:Name="myButton"
Text="My Button"
Command="{Binding ButtonClickCommand}"
CommandParameter="{x:Reference myButton}"/>
在您的視圖模型中
public YourViewModel()
{
ButtonClickCommand= new Command(ButtonClicked);
}
private async void ButtonClicked(object sender)
{
var view = sender as Xamarin.Forms.Button;
}
<Button x:Name="myButton"
Text="My Button"
Command="{Binding ButtonClickCommand}"
CommandParameter={Binding RelativeSource=
{RelativeSource
Mode=FindAncestor,
AncestorType={x:Type Button}}/>
應該可以工作,但我仍然不知道為什么需要按鈕? MVVM 的重點是分離數據和 UI。 您需要對按鈕執行的所有操作都可以通過 DataBindings 完成。
如果上述方法不起作用,唯一要嘗試的另一件事就是給按鈕一個 x:Key 和 CommandParamter = {StaticResource 'x:Key'}
一個簡單的方法是:
在 XAML 中:
<Button Text="BUTTON-TEST"
Clicked="Avaliar"
CommandParameter="like"/>
在 C# 中:
private void Avaliar(object sender, EventArgs e)
{
Console.WriteLine(((Button)sender).CommandParameter);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.