Dynami c изменение стиля вложенных элементов в DataTemplate - PullRequest
0 голосов
/ 25 апреля 2020

Я делаю свое первое приложение в xamarine, и мне нужно изменить стиль вложенного элемента в шаблоне данных в CollectionView

<ContentPage.Resources>
    <Style TargetType="yummy:PancakeView">
        <Setter Property="VisualStateManager.VisualStateGroups">
            <VisualStateGroupList>
                <VisualStateGroup x:Name="CommonStates">
                    <VisualState x:Name="Normal" />
                    <VisualState x:Name="Selected">
                        <VisualState.Setters>
                            <Setter Property="BackgroundGradientStartColor" Value="{DynamicResource BlueColor}" />
                            <Setter Property="BackgroundGradientEndColor" Value="{DynamicResource ContentPageBackgroundColor}" />
                        </VisualState.Setters>
                    </VisualState>
                </VisualStateGroup>
            </VisualStateGroupList>
        </Setter>
    </Style>
</ContentPage.Resources>

<ContentPage.Content>
        <StackLayout VerticalOptions="FillAndExpand" 
                     HorizontalOptions="FillAndExpand"
                     Padding="10">
            <CollectionView x:Name="MenuCollection" 
                            SelectionMode="Single" 
                            VerticalScrollBarVisibility="Always"
                            SelectionChanged="MenuCollection_OnSelectionChanged">

                <CollectionView.ItemsLayout>
                    <GridItemsLayout Orientation="Vertical" VerticalItemSpacing="15" HorizontalItemSpacing="15"
                                     Span="2" />
                </CollectionView.ItemsLayout>

                <CollectionView.ItemTemplate>
                    <DataTemplate>
                            <yummy:PancakeView
                                HasShadow="True"
                                WidthRequest="120" 
                                HeightRequest="120"
                                CornerRadius="30,45,45,30"
                                BorderColor="{StaticResource DrestaGrey}"
                                BorderThickness="3"
                                BackgroundGradientStartColor="{DynamicResource ContentPageBackgroundColor}"
                                BackgroundGradientEndColor="{DynamicResource BlueColor}">

                                <Label Text="{Binding Title}" Style="{StaticResource MenuLabelStyle}" />
                            </yummy:PancakeView>
                    </DataTemplate>
                </CollectionView.ItemTemplate>
            </CollectionView>
        </StackLayout>
    </ContentPage.Content>

Цель состоит в том, чтобы изменить стиль метки с MenuLabelStyle на MenuLabelSelectedStyle динамически при выборе элемента из ViewCollection.

Я попробовал триггер, я попробовал его в коде позади, но, к сожалению, безуспешно. В MenuCollection_OnSelectionChanged я не могу найти выделенный элемент (yummy: PancakeView) и заданную метку в нем.

1 Ответ

2 голосов
/ 27 апреля 2020

Вы можете использовать VisualStateManager.

VisualStateManager: https://docs.microsoft.com/en-us/dotnet/api/system.windows.visualstatemanager?view=netcore-3.1

У меня нет yummy:PancakeView, поэтому я использую StackLayout, например.

Xaml:

<ContentPage.Resources>
    <!--<Style TargetType="yummy:PancakeView">
        <Setter Property="VisualStateManager.VisualStateGroups">
            <VisualStateGroupList>
                <VisualStateGroup x:Name="CommonStates">
                    <VisualState x:Name="Normal" />
                    <VisualState x:Name="Selected">
                        <VisualState.Setters>
                            <Setter Property="BackgroundGradientStartColor" Value="{DynamicResource BlueColor}" />
                            <Setter Property="BackgroundGradientEndColor" Value="{DynamicResource ContentPageBackgroundColor}" />
                        </VisualState.Setters>
                    </VisualState>
                </VisualStateGroup>
            </VisualStateGroupList>
        </Setter>
    </Style>-->


    <Style TargetType="StackLayout">
        <Setter Property="VisualStateManager.VisualStateGroups">
            <VisualStateGroupList>
                <VisualStateGroup>
                    <VisualState x:Name="Selected">
                        <VisualState.Setters>
                            <Setter Property="BackgroundColor" Value="Accent" />
                        </VisualState.Setters>
                    </VisualState>
                    <VisualState x:Name="UnSelected">
                        <VisualState.Setters>
                            <Setter Property="BackgroundColor" Value="Blue" />
                        </VisualState.Setters>
                    </VisualState>
                </VisualStateGroup>
            </VisualStateGroupList>
        </Setter>
    </Style>
</ContentPage.Resources>

<ContentPage.Content>
    <StackLayout
        Padding="10"
        HorizontalOptions="FillAndExpand"
        VerticalOptions="FillAndExpand">
        <CollectionView
            x:Name="MenuCollection"
            ItemsSource="{Binding Infos}"
            SelectionChanged="MenuCollection_OnSelectionChanged"
            SelectionMode="Single"
            VerticalScrollBarVisibility="Always">

            <CollectionView.ItemsLayout>
                <GridItemsLayout
                    HorizontalItemSpacing="15"
                    Orientation="Vertical"
                    Span="2"
                    VerticalItemSpacing="15" />
            </CollectionView.ItemsLayout>

            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <StackLayout BackgroundColor="Blue">
                        <Label Text="{Binding Title}" />
                        <StackLayout.GestureRecognizers>
                            <TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped" />
                        </StackLayout.GestureRecognizers>
                    </StackLayout>

                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
    </StackLayout>
</ContentPage.Content>

Код:

public partial class Page1 : ContentPage
  {
    public ObservableCollection<Info> Infos { get; set; }
    public Page1()
    {
        InitializeComponent();
        Infos = new ObservableCollection<Info>
        {
            new Info(){ Title="A"},
            new Info(){ Title="B"},
            new Info(){ Title="B"},
            new Info(){ Title="C"},
            new Info(){ Title="D"}
        };

        this.BindingContext = this;
    }

    private void MenuCollection_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
    {

    }
    StackLayout lastElementSelected;
    private void TapGestureRecognizer_Tapped(object sender, EventArgs e)
    {
        //var s = (StackLayout)sender;
        //s.Style = (Style)Resources["MenuLabelSelectedStyle"];
        if (lastElementSelected != null)
            VisualStateManager.GoToState(lastElementSelected, "UnSelected");

        VisualStateManager.GoToState((StackLayout)sender, "Selected");

        lastElementSelected = (StackLayout)sender;
    }

}
public class Info
{
    public string Title { get; set; }
}

Снимок экрана:

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...