我曾尝试使用Maui Community ToolKit在XAML开关上创建一个简单的EventToCommand行为,但没有按预期工作。
我尝试将事件绑定到我的代码中的命令,当最初绑定到按钮命令时,该命令最初有效,但它不适用于开关。VisualStudio无法调试并在尝试显示CollectionView中的每个Frame时停止程序,但我相信错误是由于EventToCommandBehavior标记上的错误绑定。
XAML代码
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
xmlns:model="clr-namespace:LightApp.Models"
x:Class="LightApp.MainPage"
xmlns:viewmodel="clr-namespace:LightApp.ViewModel"
x:DataType="viewmodel:DeviceViewModel"
>
<Grid>
<CollectionView ItemSource={Binding Devices}>
<CollectionView.ItemTemplate>
<DataTemplate x:DataType="model:Device">
<Frame>
<StackLayout>
<Grid>
<Label .../>
<Image .../>
// THIS WORKS
<Button Text="Power"
Command="{Binding Source={RelativeSource AncestorType={x:Type viewmodel:DeviceViewModel}}, Path=CommandToCallCommand}" >
</Button>
// THIS DOESN'T
<Switch>
<Switch.Behaviors>
<toolkit:EventToCommandBehavior
EventName="Toggled"
Command="{Binding Source={RelativeSource AncestorType={x:Type viewmodel:DeviceViewModel}}, Path=CommandToCallCommand}" >
</toolkit:EventToCommandBehavior>
</Switch.Behaviors>
</Switch>
<Closing Tags....>
DeviceViewModel.cs
usings...
namespace LightApp.ViewModel
{
public partial class DeviceViewModel : BaseViewModel
{
public ObservableCollection<Device> Devices { get; } = new();
public DeviceViewModel(DeviceService deviceService)
{
Title = "Devices";
this.deviceService = deviceService;
}
[RelayCommand]
void CommandToCall()
{
// command here
}
}
}
1条答案
按热度按时间beq87vna1#
你可以试试下面的代码:
请注意,您应该为页面定义x:Name(x:Name=“rootPage”)