C# Xamarin表单-CommandParameter-如何通过XAML传递自定义对象?
我在视图模型中有一个名为C# Xamarin表单-CommandParameter-如何通过XAML传递自定义对象?,c#,xamarin.forms,C#,Xamarin.forms,我在视图模型中有一个名为Add的命令,它当前接收一个名为Result的参数。我现在需要更多的数据传递到命令中,这就是开关控件的IsToggled属性值 因此,如果我有以下课程: public class ResultData { public string Result { get; set; } public bool IsToggled { get; set; } } 还有一个有问题的XAML片段: <Switch IsToggled="false" ThumbCo
Add
的命令,它当前接收一个名为Result
的参数。我现在需要更多的数据传递到命令中,这就是开关
控件的IsToggled
属性值
因此,如果我有以下课程:
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
传递Result
和IsToggled
的XAML语法是什么?如果你觉得这不是正确的方法,我愿意接受其他方法
如何通过XAML传递自定义对象?使用CommandParameter传递Result&IsToggled的XAML语法是什么
对象的类型为,我们可以传递一个类对象值作为参数。要同时传递结果&i切换,请尝试将ResultData对象设置为命令参数,并在代码隐藏中获取这两个属性
我创建了一个基本的演示来测试函数,你可以参考代码
Page.xaml
<Label Text="Welcome to Xamarin.Forms!"
HorizontalOptions="CenterAndExpand">
<Label.GestureRecognizers>
<TapGestureRecognizer Command="{Binding TappedCommand}" CommandParameter="{Binding _Parameter}"/>
</Label.GestureRecognizers>
</Label>
模范班
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; }
}
只需将开关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>
<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>