繁体   English   中英

Xamarin Forms - 命令参数 - 如何通过 Z8CBFD56579569C416DDED1B21D83 传递自定义 object?

[英]Xamarin Forms - CommandParameter - How to pass custom object via XAML?

我在视图 model 中有一个名为Add的命令,它目前接受一个名为Result的参数。 我现在需要将更多数据传递到命令中,这就是Switch控件的IsToggled属性值。

因此,如果我有以下 class:

public class ResultData
{
    public string Result { get; set; }
    public bool IsToggled { get; set; }
}

以及有问题的 XAML 的片段:

 <Switch IsToggled="false" ThumbColor="Black" OnColor="LimeGreen" HorizontalOptions="End" VerticalOptions="Center" >
    <Switch.Behaviors>
         <behaviours:EventToCommandBehavior EventName="Toggled"                                                            
           Command="{Binding BindingContext.Add, Source={x:Reference 
              MyPageContent}}" 
           CommandParameter="{Binding Result}" />
    </Switch.Behaviors>
 </Switch>

使用CommandParameter传递ResultIsToggled的 XAML 语法是什么? 如果您认为这不是正确的方法,我对其他方法持开放态度。

您可以这样做,只需将您的开关 BindingContext 设置为 Result 并将您的开关作为参数传递给 CommandParameter,然后您可以从该参数获取开关的任何属性。

<Switch IsToggled="false" ThumbColor="Black" OnColor="LimeGreen" HorizontalOptions="End" VerticalOptions="Center" BindingContext="{Binding Result}" x:Name="switch">
    <Switch.Behaviors>
         <behaviours:EventToCommandBehavior EventName="Toggled"                                                            
           Command="{Binding BindingContext.Add, Source={x:Reference 
              MyPageContent}}" 
           CommandParameter="{Binding Source={x:Reference switch}}" />
    </Switch.Behaviors>
</Switch>

如何通过 XAML 传递自定义 object? 使用 CommandParameter 传递 Result 和 IsToggled 的 XAML 语法是什么?

CommandParameter的类型是object ,我们可以传递一个 class object 值作为参数。 要同时传递ResultIsToggled ,请尝试将 ResultData object 设置为CommandParameter并在后面的代码中获取这两个属性。

我创建了一个基本的演示来测试function,你可以参考代码。

页.xaml

<Label Text="Welcome to Xamarin.Forms!"
       HorizontalOptions="CenterAndExpand">
    <Label.GestureRecognizers>
        <TapGestureRecognizer Command="{Binding TappedCommand}" CommandParameter="{Binding _Parameter}"/>
    </Label.GestureRecognizers>
</Label>

页码.xaml.cs

public partial class Page4 : ContentPage
{
    public Page4()
    {
        InitializeComponent();

        BindingContext = new Model_4();
    }
}

Model class

public class Model_4
{
    public TheParameter _Parameter { get; set; }

    public ICommand TappedCommand { private set; get; }

    public Model_4()
    {
        TappedCommand = new Command(OnTapped);
        _Parameter = new TheParameter { Property_1 = "Property_1", Property_2 = "Property_2" };
    }

    private void OnTapped(object obj)
    {
        var theParameter = obj as TheParameter;
        Console.WriteLine(theParameter.Property_1);
        Console.WriteLine(theParameter.Property_2);
    }
}

public class TheParameter
{
    public string Property_1 { get; set; }
    public string Property_2 { get; set; }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM