我正在制作一个带有两个单选按钮的视图,唯一的问题是CheckedChanged属性不能绑定到带有RelayCommand注释的方法。根据Visual Studio上的错误显示,它只能绑定到一个属性或值。是否有任何方法可以将此属性绑定到视图模型上的方法?
这是单选按钮:
<RadioButton Value="Player1"
Grid.Row="1"
Grid.ColumnSpan="2"
Content="{Binding Name1}"
BorderColor="#FF1111"
BorderWidth="20"
VerticalOptions="Center"
IsChecked= "False"
CheckedChanged= "{Binding ChangeCurrentPlayer2Command}"
/>
和中继命令:
void ChangeCurrentPlayer2()
{
if (currentPlayer == Player1)
{
currentPlayer = this.Player2;
}
else
{
currentPlayer = this.Player1;
}
}
我想要的是绑定一个viewmodel方法到事件checkedChanged的单选按钮,我知道如何做到这一点使用一个正常的按钮,通过使用RelayCommand注释。
正如Jason所说,你可以使用。net MAUI Community Toolkit中的EventToCommandBehavior来实现它。
Page.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:viewmodel="clr-namespace:MauiApp1.ViewModels"
x:Class="MauiApp1.NewPage2"
Title="NewPage2">
<ContentPage.BindingContext>
<viewmodel:VM/>
</ContentPage.BindingContext>
<VerticalStackLayout>
<RadioButton Value="Player1"
x:Name="this"
Content="{Binding Name1}"
VerticalOptions="Center"
IsChecked= "False">
<RadioButton.Behaviors>
<toolkit:EventToCommandBehavior
EventName="CheckedChanged"
Command="{Binding ChangeCurrentPlayer2Command}"
CommandParameter="{Binding Source={Reference this}}"/>
</RadioButton.Behaviors>
</RadioButton>
</VerticalStackLayout>
</ContentPage>
ViewModel:
namespace MauiApp1.ViewModels
{
public class VM : INotifyPropertyChanged
{
public string name1;
public string Name1
{
get => name1;
set
{
name1 = value;
OnPropertyChanged(nameof(Name1));
}
}
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public ICommand ChangeCurrentPlayer2Command { get; set; }
public VM()
{
Name1 = "Player1";
ChangeCurrentPlayer2Command = new Command<object>(ChangeCurrentPlayer2);
}
public void ChangeCurrentPlayer2(object content)
{
var radiobutton = content as RadioButton;
if (Name1 != radiobutton.Value.ToString())
{
Name1 = radiobutton.Value.ToString();
}
else
{
Name1 = "Player2";
}
}
}
}
单击RadioButton时,如果Value
与Content
绑定的值相同,则改变Content
。