按钮的绑定命令



我有转盘视图和绑定属性:

<ContentView>
<controls:CarouselViewControl x:Name="CarouselData" ItemsSource="{Binding StartDisplay}"
ShowIndicators="True"
ShowArrows="False"
IndicatorsTintColor="BurlyWood" CurrentPageIndicatorTintColor="DarkGoldenrod">
<controls:CarouselViewControl.ItemTemplate>
<DataTemplate >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="100" />
<RowDefinition Height="100" />
</Grid.RowDefinitions>
<Image  Grid.RowSpan="3" Aspect="AspectFill"  Source="{Binding Image}"/>
<ContentView Grid.Row="0" Padding="60,30,60,0">
</ContentView>
<ContentView Grid.Row="1" Padding="20,10,20,50">
<Label Text="{Binding Message}"
TextColor="Black"
FontSize="20"
HorizontalTextAlignment="Center" />
</ContentView>
<ContentView Grid.Row="2" Padding="20,10,20,50">
<Button Text="Getted start" IsVisible="{Binding VisibleStartButton}"/>
</ContentView>
</Grid>
</DataTemplate>
</controls:CarouselViewControl.ItemTemplate>
</controls:CarouselViewControl>
</ContentView>

我为CarouselView指向项目源。类模型视图:

public class StartPageViewModel: BaseViewModel // ViewModel
{
private ObservableCollection<DataCarouselView> startDisplay;
public ObservableCollection<DataCarouselView> StartDisplay
{
get => startDisplay; set => SetProperty(ref startDisplay, value);
}
public StartPageViewModel()
{
StartDisplay = new ObservableCollection<DataCarouselView>(new[]
{
new DataCarouselView("back_1.png", "test1"),
new DataCarouselView("back_2.png", "test2"),
new DataCarouselView("back_3.png", "test3"),
new DataCarouselView("back_4.png", "test4", true)
});
OpenMenuPageCommand = new OpenMenuPageCommand(this);
}
}

类别型号:

public class DataCarouselView // Model
{
public string Image { get; set; }
public string Message { get; set; }
public bool VisibleStartButton { get; set; }
public DataCarouselView(string image, string message, bool vis = false)
{
Image = image;
Message = message;
VisibleStartButton = vis;
}
}

一切正常。

我想将的命令添加到按钮中。我创建命令类:

public class OpenMenuPageCommand : ICommand
{
public event EventHandler CanExecuteChanged;
private StartPageViewModel viewModel;
public OpenMenuPageCommand(StartPageViewModel vm)
{
viewModel = vm;
}
public bool CanExecute(object parameter)
{
return viewModel != null;
}
public void Execute(object parameter)
{
if (CanExecute(parameter)) 
viewModel.OpenMenuPage();
}
}

和类ViewModel:中的属性

public ICommand OpenMenuPageCommand { get; }

和类ViewModel:中的方法命令

public async void OpenMenuPage()
{
await navigation.PushAsync(new MenuPage());
}

如何为按钮绑定命令?谢谢

您需要使用相对源绑定使其在中工作

首先将根控件的名称设置如下:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Name="InfoView"
x:Class="InfoSeries.Views.InfoView">

然后您可以引用InfoView,以便将ButtonCommand与ViewModel:绑定

<Button Text="Getted start" IsVisible="{Binding VisibleStartButton}" Command="{Binding Source={x:Reference InfoView}, Path=BindingContext.OpenMenuPageCommand}"/>

最新更新