简体   繁体   English

在 UWP C# 上选择时更改颜色

[英]Change color when selected on UWP C#

I need to change the color of a rectangle in a GridView when the item is selected.选择该项目时,我需要更改 GridView 中矩形的颜色。

Unselected item未选择的项目

Selected item所选项目

My Main Page in XAML.我在 XAML 中的主页。

<Page
    x:Class="GridViewWithSelectedItem.Views.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:views="using:GridViewWithSelectedItem.Views"
    Style="{StaticResource PageStyle}"
    mc:Ignorable="d">
    <Page.Resources>
        <DataTemplate x:Key="TileTemplate" x:DataType="views:Article">
            <Border BorderThickness="2,2,2,2" BorderBrush="#FF868484" Margin="3,3,3,3" HorizontalAlignment="Stretch" MaxWidth="600" MinWidth="525">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="10"/>
                        <ColumnDefinition/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition/>
                        <RowDefinition Height="60"/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <Rectangle Fill="Black" Grid.RowSpan="3"/>
                    <StackPanel Orientation="Horizontal"  Grid.Row="0" Grid.Column="1">
                        <TextBlock FontSize="20" Margin="0,0,5,0" TextWrapping="Wrap" Foreground="DarkBlue" FontWeight="Bold" Text="{x:Bind Number}"/>
                        <TextBlock FontSize="20" TextWrapping="Wrap" Foreground="DarkBlue" Text="{x:Bind Title}" FontWeight="Bold"/>
                    </StackPanel>
                    <TextBlock Grid.Row="1" Grid.Column="1" FontSize="20" Text="{x:Bind Description}" TextWrapping="WrapWholeWords"/>
                    <StackPanel Background="LightBlue" Padding="5,0,0,0"  Grid.Row="2" Grid.Column="1">
                        <StackPanel Orientation="Horizontal">
                        <TextBlock FontSize="20" Margin="0,0,5,0" TextWrapping="Wrap">Date :</TextBlock>
                        <TextBlock Foreground="Red" FontSize="20" TextWrapping="Wrap" Text="{x:Bind Date}" FontWeight="Bold"/>
                        </StackPanel>
                    </StackPanel>
                </Grid>
            </Border>
        </DataTemplate>
    </Page.Resources>
    <Grid x:Name="ContentArea" Margin="{StaticResource MediumLeftRightMargin}">
        <Grid Background="White" VerticalAlignment="Top" HorizontalAlignment="Stretch" Margin="0,25,0,0">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="600"/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="60"/>
                <RowDefinition Height="800"/>
            </Grid.RowDefinitions>
            <TextBlock Text="The Guardian" FontSize="35" FontWeight="Bold" Grid.ColumnSpan="2" HorizontalAlignment="Center"/>
            <GridView
                BorderThickness="2,2,0,2" BorderBrush="#FF868484"
                MinWidth="600"
                Grid.Column="0"
                Grid.Row="1"
                Padding="5,5,5,5"
                HorizontalAlignment="Center"
                CanDragItems="False"
                IsItemClickEnabled="true"
                IsTapEnabled="False"
                IsSwipeEnabled="False"
                ItemsSource="{x:Bind Articles}"
                ItemTemplate="{StaticResource TileTemplate}"
                SelectedItem="{x:Bind Mode=TwoWay, Path=SelectedArticle}"
                
            />
            <RelativePanel  Grid.Row="1" Grid.Column="1" Background="WhiteSmoke" BorderThickness="2" BorderBrush="#FF868484" Padding="10">
                <Grid RelativePanel.AlignLeftWithPanel="True" RelativePanel.AlignRightWithPanel="True">
                    <Grid VerticalAlignment="Top">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition/>
                        </Grid.ColumnDefinitions>
                        <Grid.RowDefinitions>
                            <RowDefinition/>
                            <RowDefinition/>
                        </Grid.RowDefinitions>
                        <StackPanel Orientation="Horizontal"  Grid.Row="0">
                            <TextBlock FontSize="20" Margin="0,0,5,0" TextWrapping="Wrap" Foreground="DarkBlue" FontWeight="Bold" Text="{x:Bind Path=SelectedArticle.Number, Mode=OneWay}"/>
                            <TextBlock FontSize="20" TextWrapping="Wrap" Foreground="DarkBlue" Text="{x:Bind Path=SelectedArticle.Title, Mode=OneWay}" FontWeight="Bold"/>
                        </StackPanel>
                        <TextBlock Grid.Row="1" FontSize="20" Text="{x:Bind Path=SelectedArticle.Description, Mode=OneWay}" TextWrapping="WrapWholeWords"/>
                    </Grid>
                </Grid>
                <RelativePanel Background="LightBlue" Padding="5,0,0,0" RelativePanel.AlignBottomWithPanel="True" RelativePanel.AlignLeftWithPanel="True" RelativePanel.AlignRightWithPanel="True">
                    <StackPanel Orientation="Horizontal">
                        <TextBlock FontSize="20" Margin="0,0,5,0" TextWrapping="Wrap">Date :</TextBlock>
                        <TextBlock Foreground="Red" FontSize="20" TextWrapping="Wrap" Text="{x:Bind Path=SelectedArticle.Date, Mode=OneWay}" FontWeight="Bold"/>
                    </StackPanel>
                </RelativePanel>
            </RelativePanel>
        </Grid>
    </Grid>
</Page>

And the class of my XAML Page.还有我的 XAML 页面的 class。

using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;

using Windows.UI.Xaml.Controls;

namespace GridViewWithSelectedItem.Views
{
    public sealed partial class MainPage : Page, INotifyPropertyChanged
    {
        public ObservableCollection<Article> Articles;

        private Article _selectedArticle;

        public Article SelectedArticle
        {
            get { return _selectedArticle; }
            set { Set(ref _selectedArticle, value); }
        }

        public MainPage()
        {
            InitializeComponent();
            Articles = new ObservableCollection<Article>();
            Articles.Add(new Article(0, "Uighurs", "Being young' leads to detention in China's Xinjiang region", DateTime.Parse("09/12/2020")));
            Articles.Add(new Article(1, "Brexit", "Chances of Brexit deal hang on Boris Johnson and Ursula von der Leyen dinner", DateTime.Parse("09/12/2020")));
            Articles.Add(new Article(2, "Environment", "Secretive ‘gold rush’ for deep-sea mining dominated by handful of firms", DateTime.Parse("09/12/2020")));
            Articles.Add(new Article(3, "Juukan Gerge induiry", "Juukan Gorge inquiry: Rio Tinto's decision to blow up Indigenous rock shelters 'inexcusable'", DateTime.Parse("09/12/2020")));
            Articles.Add(new Article(4, "Australia", "British journalist uncovered Australian woman's alleged plan to kill parents on dark web, police say", DateTime.Parse("09/12/2020")));
            Articles.Add(new Article(5, "Coronavirus", "Nine out of 10 in poor nations to miss out on inoculation as west buys up Covid vaccines", DateTime.Parse("09/12/2020")));
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void Set<T>(ref T storage, T value, [CallerMemberName]string propertyName = null)
        {
            if (Equals(storage, value))
            {
                return;
            }

            storage = value;
            OnPropertyChanged(propertyName);
        }

        private void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    public class Article
    {
        public int Number { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public DateTime Date { get; set; }

        public Article(int number, string title, string description, DateTime date)
        {
            Number = number;
            Title = title;
            Description = description;
            Date = Date;
        }
    }
}

I see AutomationProperty.name can help me but i don't understand how to use it.我看到 AutomationProperty.name 可以帮助我,但我不明白如何使用它。 I found a way to change the color of a selected item in my class but i need to recreate the collection and i cost lot of resources.我找到了一种方法来更改 class 中选定项目的颜色,但我需要重新创建集合并且我花费了大量资源。 I think its possible to make it in XAML code.我认为它可以在 XAML 代码中实现。

Edit: I made a simple exemple of my code.编辑:我做了一个简单的代码示例。

OneDrive link OneDrive 链接

You could add a Brush property into the Article class, and bind the Brush property to Rectangle.Fill property of your DataTemplate to change the color when an item of GridView control is selected.您可以在Article class 中添加 Brush 属性,并将 Brush 属性绑定到DataTemplateRectangle.Fill属性以在选择 GridView 控件的项目时更改颜色。

Please check the following code:请检查以下代码:

In DataTemplate of your xaml file:在 xaml 文件的DataTemplate中:

<Rectangle x:Name="rectangle" Fill="{x:Bind Brush}" Grid.RowSpan="3"/>
……
<GridView ……  SelectionChanged="GridView_SelectionChanged" />

In code-behind:在代码隐藏中:

public class Article
{
    ……
    public SolidColorBrush Brush { get; set; }

    public Article(int number, string title, string description, DateTime date)
    {
        ……
        Brush = new SolidColorBrush(Colors.Black);
    }
}

Add a _preSelectedArticle property to save the previous item in MainPage class:添加_preSelectedArticle属性以保存MainPage class 中的上一项:

private Article _preSelectedArticle;

Change the value of Brush property of selected item and previous selected item:更改选中项和上一个选中项的Brush属性值:

private void GridView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if(_preSelectedArticle==null)
    {
        SelectedArticle.Brush.Color = Colors.Green;
        _preSelectedArticle = SelectedArticle;
    }
    if (_preSelectedArticle!=null&&_preSelectedArticle!= SelectedArticle)
    {
        _preSelectedArticle.Brush.Color = Colors.Black;
        SelectedArticle.Brush.Color = Colors.Green;
        _preSelectedArticle = SelectedArticle;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM