我有一个设置,一个可观察的集合绑定到一个列表视图,当一个列表视图项目被点击一个隐藏的堆栈出现,并显示3个按钮,供用户继续他们的页面
菜单:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:dogs="clr-namespace:MBRMobile.ViewModels.Dogs"
x:Class="MBRMobile.Views.Dogs.ViewDog">
<ContentPage.Content>
<StackLayout>
<ListView x:Name="ViewListSource"
HasUnevenRows="true"
ItemsSource="{Binding DogItemsSource}"
ItemTapped="ListView_Tapped">
<ListView.Header>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Label Grid.Column="0"
FontAttributes="Bold"
Text="Name" />
<Label Grid.Column="1"
FontAttributes="Bold"
Text="Breed" />
<Label Grid.Column="2"
FontAttributes="Bold"
Text="From" />
<Label Grid.Column="3"
Text="Intake"
FontAttributes="Bold" />
</Grid>
</ListView.Header>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="{Binding VisibilityHeight}" />
</Grid.RowDefinitions>
<Label Grid.Column="0"
Grid.Row="0"
Text="{Binding DogName}" />
<Label Grid.Column="1"
Grid.Row="0"
Text="{Binding DogBreed}" />
<Label Grid.Column="2"
Grid.Row="0"
Text="{Binding ReceivedFrom}" />
<Label Grid.Column="3"
Grid.Row="0"
Text="{Binding IntakeDate}" />
<StackLayout Orientation="Horizontal"
IsVisible="{Binding IsVisible}"
Grid.Row="1">
<StackLayout.BindingContext>
<dogs:ViewVM />
</StackLayout.BindingContext>
<Button Text="Update"
Command="{Binding UpdateDog_Clicked}"
CommandParameter="{Binding DogID}"/>
<Button Text="Remove"
Command="{Binding RemoveDog_Clicked}"
CommandParameter="{Binding DogID}" />
<Button Text="Schedule"
Command="{Binding ScheduleDog_Clicked}"
CommandParameter="{Binding DogID}" />
</StackLayout>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
</ContentPage>
按钮绑定命令不在绑定到列表视图的DogItemsSource中,这在vs中抛出“not found”错误。
<StackLayout.BindingContext>
<dogs:ViewVM />
</StackLayout.BindingContext>
它引用菜单的视图模型,按钮出现几秒钟,然后按钮消失。我只能假设,因为它重新加载页面?DogItemsSource和按钮命令都在同一个视图模型和类中。我在这里错过了什么?
1条答案
按热度按时间velaa5lx1#
DogItemsSource和button命令都在同一个视图模型和类中。
你想把StackLayout的BindingContext设置到ViewModel,因为Button Command设置在ViewModel中,对吧?你可以简单地这样设置:
然后在page的code behind中,设置ViewDog页面的BindingContext:
现在在StackLayout中,BindingContext将是ViewModel(与ViewDog页面相同)。
但是,考虑到您的代码细节,您还将CommandParameter绑定到 DogID,我假设 DogID 是在Dog模型中定义的,那么Command和CommandParameter的BindingContext是不同的,如果将StackLayout的BindingContext设置为ViewModel,可能会产生矛盾,对吧?(如果理解有误,请忽略以下内容)
所以我可以给予另一个解决方案,即Xamarin.Forms Relative Bindings:
通过这种方式,Button命令的BindingContext是ViewModel,而CommandParameter仍然绑定到ObservableCollection中的每个dog项。
希望能成功。