簡體   English   中英

每當值更改時,更改 uwp 中列表視圖項的背景顏色

[英]Change background color of list view item in uwp whenever the value changes

我有一個列表視圖,其中的值從不同的線程不斷更新。 我想根據項目的值來改變背景的顏色。 在閱讀了很多之后,我得出以下結論:

  • 為列表視圖項設置背景顏色的正確方法是通過樣式選擇器。
  • 樣式選擇器在列表的初始化中只被調用一次。

我怎樣才能實現這種簡單的行為?

xaml:

<Page
    x:Class="MyProject.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:MyProject"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Grid>
        <ListView ItemsSource="{x:Bind ViewModel.DataRef.Values, Mode=OneWay}" HorizontalAlignment="Center" VerticalAlignment="Center">
            <ListView.ItemTemplate>
                <DataTemplate x:DataType="local:ValWrapper">
                    <TextBlock Text="{x:Bind Val, Mode=OneWay}"/>
                </DataTemplate>
            </ListView.ItemTemplate>
            <ListView.ItemContainerStyleSelector>
                <local:CustomItemContainerStyleSelector>
                    <local:CustomItemContainerStyleSelector.Bad>
                        <Style TargetType="ListViewItem">
                            <Setter Property="Background" Value="Red"/>
                            
                        </Style>
                    </local:CustomItemContainerStyleSelector.Bad>

                    <local:CustomItemContainerStyleSelector.Good>
                        <Style TargetType="ListViewItem">
                            <Setter Property="Background" Value="Green"/>
                        </Style>
                    </local:CustomItemContainerStyleSelector.CloseToBad>
                </local:CustomItemContainerStyleSelector>
            </ListView.ItemContainerStyleSelector>
        </ListView>
    </Grid>
</Page>

CS:

public sealed partial class MainPage : Page
{
    public ViewModel ViewModel { get; set; }

    public MainPage()
    {
        this.InitializeComponent();
        this.ViewModel = new ViewModel();

    }

}

public class CustomItemContainerStyleSelector : StyleSelector
{
    public Style Bad { get; set; }
    public Style Good { get; set; }


    protected override Style SelectStyleCore(object item, DependencyObject container)
    {
        double threshold = 1;
        ValWrapper v = (ValWrapper)item;
        if (v.Val <= threshold)
        {
            return Bad;
        }
        else {
            return Good;
        }
    }
}

每當數據更改時,都會調用“NotifyPropertyChanged”(實現 INotifyPropertyChanged)。

請檢查以下步驟:

  1. 設置一個臨時變量_tempValue來記錄以前的數字。
  2. Background屬性綁定到IsUpdate ,初始值全部為false
  3. 如果數字發生變化,請將IsUpdate設置為true ,然后ListViewItemBackground變為red

XAML:

<Page
    x:Class="Permisson.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Permisson"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Page.Resources>
        <local:ColorConverter x:Key="ColorConverter"/>
    </Page.Resources>
    <Grid>
        <StackPanel>
            <ListView ItemsSource="{x:Bind ViewModel.DataRef, Mode=OneWay}" HorizontalAlignment="Center" VerticalAlignment="Center">
                <ListView.ItemTemplate >
                    <DataTemplate x:DataType="local:ValWrapper">
                        <Grid Background="{Binding IsUpdate, Converter={StaticResource ColorConverter},Mode=OneWay}">
                            <TextBlock Text="{Binding Val, Mode=OneWay}"/>
                        </Grid>
                    </DataTemplate>

                </ListView.ItemTemplate>
             
            </ListView>
            <Button Content="ChangeNum" Click="Button_Click"/>
            <Button Content="ChangeNum2" Click="Button_Click_1"/>        
        </StackPanel>
   
    </Grid>
</Page>

后面的代碼:

namespace Permisson
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public ViewModel ViewModel { get; set; }

        public MainPage()
        {
            this.InitializeComponent();

            this.ViewModel = new ViewModel();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var v = ViewModel.DataRef[0];
       
            v.Val = 9;
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            var v = ViewModel.DataRef[1];         
            v.Val = 10;
        }
    }
    public class ViewModel
    {
        private ObservableCollection<ValWrapper> dataRef = new ObservableCollection<ValWrapper>()
        {
            new ValWrapper {Val=22,Brush=new SolidColorBrush (Colors.Green),IsUpdate = false },
            new ValWrapper {Val=25,Brush=new SolidColorBrush (Colors.Green),IsUpdate = false},
            new ValWrapper {Val=35,Brush=new SolidColorBrush (Colors.Green),IsUpdate = false},
            new ValWrapper {Val=45,Brush=new SolidColorBrush (Colors.Green),IsUpdate = false },
            new ValWrapper {Val=55,Brush=new SolidColorBrush (Colors.Green),IsUpdate = false},
            new ValWrapper {Val=65,Brush=new SolidColorBrush (Colors.Green),IsUpdate = false }

        };
        public ObservableCollection<ValWrapper> DataRef { get { return dataRef; } }

    }
    public class ColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            var color = new SolidColorBrush();
            if ((bool)value)
            {
                color.Color = Colors.Red;
            }
            else
            {
                color.Color = Colors.Green;

            }
            return color;
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotImplementedException();
        }
    }


    public class ValWrapper : INotifyPropertyChanged
    {
        private int val;
        private SolidColorBrush brush;
        public SolidColorBrush Brush
        {
            get { return brush; }
            set
            {
                brush = value;
                RaisePropertyChanged();
            }
        }


        private int _tempValue;
        public int Val
        {
            get { return val; }
            set
            {
               if(_tempValue != value && _tempValue != 0)
                {
                    IsUpdate = true;
                }
                val = value;
                RaisePropertyChanged();
                _tempValue = val;
            }
        }
        private bool _isUpdate;
        public bool IsUpdate
        {
            set
            {
                _isUpdate = value;
                RaisePropertyChanged();
            }
            get
            {
                return _isUpdate;

            }
        }


        public event PropertyChangedEventHandler PropertyChanged;
        public void RaisePropertyChanged([CallerMemberName] string propertyname = null)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyname));

            }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM