Представление списка при изменении контекста привязки очищает текст кнопки

Я уже некоторое время сталкиваюсь с этим странным поведением, и я не могу понять, что именно вызывает проблему.

Я использую FreshMvvm, и у меня есть ListView с двумя кнопками внутри.

Теперь проблема в том, что одна из кнопок получает текст от Binding. Во-вторых, чтобы назначить кнопку с помощью команды щелчка, мне пришлось следовать это.

Теперь, после добавления этого, событие щелчка работает отлично, но привязка текста не работает. Я подозревал, что это произошло из-за изменения контекста привязки, что, я уверен, является всей причиной, но я не могу найти способ исправить это, мой код списка следующее:

<ListView Grid.Row="1" 
          ItemsSource="{Binding CategoryAndActivities}" 
          x:Name="WishListName"
          HorizontalOptions="FillAndExpand" 
          VerticalOptions="FillAndExpand" >
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>                                        
                    <Frame>
                        <Grid VerticalOptions="FillAndExpand" 
                              HorizontalOptions="FillAndExpand">
                            <Grid.RowDefinitions>
                                <RowDefinition Height="Auto" />
                                <RowDefinition Height="*" />
                                <RowDefinition Height="Auto" />
                            </Grid.RowDefinitions>
                            <!--Image and Title-->
                            <AbsoluteLayout Grid.Row="0"
                                            HeightRequest="70" 
                                            IsClippedToBounds = "true">
                                <ffimageloading:CachedImage Source="{Binding ActivityImage}" 
                                                            Aspect="AspectFill" 
                                                            AbsoluteLayout.LayoutFlags="All"
                                                            AbsoluteLayout.LayoutBounds="0.0, 0.0, 0.3, 0.85" 
                                                            Margin="5, 0, 5, 5" 
                                                            ErrorPlaceholder="nopreviewlandscape" 
                                                            LoadingPlaceholder="loadingicon"/>
                                <Label x:Name="ActivityNameLabel" 
                                       Text="{Binding ActivityName}" 
                                       FontAttributes="Bold" 
                                       VerticalTextAlignment="Start"
                                       TextColor="{StaticResource price_text_color}" 
                                       FontSize="Small"
                                       AbsoluteLayout.LayoutFlags="All"
                                       AbsoluteLayout.LayoutBounds="1.0, 0.0, 0.7, 0.85" 
                                       Margin="5, 5, 5, 5">
                                </Label>
                            </AbsoluteLayout>
                            <!--Descp-->
                            <StackLayout Grid.Row = "1" 
                                         IsClippedToBounds="true">
                                <Label Text="{Binding AcitivityDescription}" 
                                       FontSize="Small" 
                                       LineBreakMode="WordWrap" 
                                       Margin="5, 0, 5, 5"/>
                            </StackLayout>
                            <Grid BackgroundColor="White" 
                                  Grid.Row = "2" 
                                  VerticalOptions="FillAndExpand" 
                                  HorizontalOptions="FillAndExpand">
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="50*"/>
                                    <ColumnDefinition Width="50*"/>
                                </Grid.ColumnDefinitions>

                                <Button BackgroundColor="{StaticResource ColorBrandingYellow}"  
                                        HorizontalOptions="FillAndExpand"  
                                        Command="{Binding AddToWishListCommand}" 
                                        Grid.Column="0" 
                                        BindingContext="{Binding Source={x:Reference ListName}, Path=BindingContext}" 
                                        CommandParameter="{Binding Source={x:Reference ActivityNameLabel},Path=BindingContext}" 
                                        TextColor="Black" 
                                        Text="{resourceLocal:Translate addToWishlist}" 
                                        FontSize = "Small" />
                                <Button BackgroundColor="{StaticResource ColorBrandingYellow}" 
                                        HorizontalOptions="FillAndExpand" 
                                        Grid.Column="1" 
                                        TextColor="Black" 
                                        Text="{Binding ActivityAmount}" 
                                        FontSize = "Small" 
                                        Command="{Binding GoFeatureActivityDetail}" 
                                        BindingContext="{Binding Source={x:Reference ListName}, Path=BindingContext}"
                                        CommandParameter="{Binding Source={x:Reference ActivityNameLabel},Path=BindingContext}"/> 
                            </Grid>
                        </Grid>
                    </Frame>                                        
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

Проблема заключается в кнопке с привязкой в ​​виде текста, что случается, текст просто отображается пустым, хотя данные действительно существуют.

Код события Click выглядит следующим образом:

public ICommand GoFeatureActivityDetail { get; set; }

public BrowseFeaturesPageModel()
{
    AddToWishListCommand = new Command(WishListCommand);
    GoFeatureActivityDetail = new Command(FeatureActivityDetailCommand);
}

private async void FeatureActivityDetailCommand(object obj)
{}

person FreakyAli    schedule 09.04.2018    source источник


Ответы (1)


Правильная мысль, плохая реализация.

Здесь происходит то, что вы изменили BindingContext кнопки, и теперь она больше не может «видеть» свойство ActivityAmount элемента, потому что она «смотрит» на объект BrowseFeaturesPageModel. Вы можете сделать все проще, изменив BindingContext только там, где вы будете использовать, а не весь View (кнопка в данном случае):

<Button BackgroundColor="{StaticResource ColorBrandingYellow}" 
        HorizontalOptions="FillAndExpand" 
        Grid.Column="1" 
        TextColor="Black" 
        Text="{Binding ActivityAmount}" 
        FontSize = "Small" 
        Command="{Binding BindingContext.GoFeatureActivityDetail, Source={x:Reference ListName}}" 
        CommandParameter="{Binding .}"/> 
person Diego Rafael Souza    schedule 09.04.2018
comment
В любом случае, решил это час назад, спасибо за ответ, и это правильно, вы только что сэкономили мне время, чтобы ответить на него самому, спасибо, ночные коды могут быть глупыми, вы видите - person FreakyAli; 09.04.2018
comment
Ха-ха, полностью с вами согласен! - person Diego Rafael Souza; 09.04.2018