Domanda

Ho alcune celle in un datagrid e vorrei evidenziare le celle in alcune colonne rosse quando il loro valore è 0. Non sono sicuro di come affrontare questo.

Ho guardato questa domanda: WPF: come evidenziare tutte le celle di un datagrid che incontra una condizione? Ma nessuna delle soluzioni ha funzionato per me.

Con l'uso di trigger di stile, sembra che i trigger debbano essere applicati sulle proprietà. Quando faccio qualcosa come non succede nulla (suppongo perché c'è di più nel contenuto di un valore semplice).

Con l'ultima soluzione suggerita stavo ottenendo un problema a tempo di compilazione che sembrava essere una manifestazione di un bug che è stato in vs da un po 'di tempo: La classe di associazione personalizzata non funziona correttamente

Qualche idea su come posso raggiungere questo obiettivo?

Qualcuno ha qualche idea?

È stato utile?

Soluzione

Il modo migliore per modificare il colore di sfondo di una cella in base al valore di un datagridcell è definire un datatemplate di dati per DataGridTemplateColumn con un convertitore per alterare il colore di sfondo della cella. Il campione fornito qui utilizza MVVM.

Le parti dei tasti da cercare nel seguente esempio includono:

1: XAML che converte un numero intero (fattore) nel modello in un colore:

<TextBlock Text="{Binding Path=FirstName}" 
           Background="{Binding Path=Factor, 
             Converter={StaticResource objectConvter}}" />

2: convertitore che restituisce un solidcolorbrush basato su una proprietà integer nel modello:

public class ObjectToBackgroundConverter : IValueConverter

3: ViewModel che modifica il valore intero nel modello tra 0 e 1 da un pulsante Fare clic per sparare un evento che cambia il colore nel convertitore.

private void OnChangeFactor(object obj)
{
  foreach (var customer in Customers)
  {
    if ( customer.Factor != 0 )
    {
      customer.Factor = 0;
    }
    else
    {
      customer.Factor = 1;
    }
  }
}

4: Modello implementa inotifyproperty -changed usato per sparare l'evento per modificare il colore di sfondo chiamando suPropertyChanged

private int _factor = 0;
public int Factor
{
  get { return _factor; }
  set
  {
    _factor = value;
    OnPropertyChanged("Factor");
  }
}

Ho fornito tutti i bit necessari qui nella mia risposta, ad eccezione delle parti fondamentali utilizzate come fondamento del modello MVVM che include ViewModelBase (inotifypropertyChanged) e delegateCommand in cui puoi trovare tramite Google. Si noti che legato il datacontext della vista su ViewModel nel costruttore del codice-BEHIND. Posso pubblicare questi bit aggiuntivi se necessario.

Ecco il xaml:

<Window x:Class="DatagridCellsChangeColor.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:Helpers="clr-namespace:DatagridCellsChangeColor.Converter" 
    Title="MainWindow" 
    Height="350" Width="525">
  <Window.Resources>
    <Helpers:ObjectToBackgroundConverter x:Key="objectConvter"/>
   /Window.Resources>
 <Grid>
  <Grid.RowDefinitions>
   <RowDefinition Height="Auto"/>
   <RowDefinition/>
  </Grid.RowDefinitions>
  <Button Content="Change Factor" Command="{Binding Path=ChangeFactor}"/>
  <DataGrid
   Grid.Row="1"
   Grid.Column="0"
   Background="Transparent" 
   ItemsSource="{Binding Customers}" 
   IsReadOnly="True"
   AutoGenerateColumns="False">
   <DataGrid.Columns>
    <DataGridTemplateColumn
      Header="First Name" 
      Width="SizeToHeader">
      <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
          <TextBlock Text="{Binding Path=FirstName}" 
                      Background="{Binding Path=Factor, 
                      Converter={StaticResource objectConvter}}" />
        </DataTemplate>
      </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
    <DataGridTemplateColumn
      Header="Last Name" 
      Width="SizeToHeader">
      <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
          <TextBox Text="{Binding Path=LastName}" />
        </DataTemplate>
      </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
   </DataGrid.Columns>
  </DataGrid>
 </Grid>
</Window>

Ecco il convertitore:

using System;
using System.Drawing;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Media;
using Brushes = System.Windows.Media.Brushes;

namespace DatagridCellsChangeColor.Converter
{
  [ValueConversion(typeof(object), typeof(SolidBrush))]
  public class ObjectToBackgroundConverter : IValueConverter
  {
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
      int c = (int)value;

      SolidColorBrush b;
      if (c == 0)
      {
        b = Brushes.Gold;
      }
      else
      {
        b = Brushes.Green;
      }
      return b;
    }

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

Ecco il ViewModel:

using System.Collections.ObjectModel;
using System.Windows.Input;
using DatagridCellsChangeColor.Commands;
using DatagridCellsChangeColor.Model;

namespace DatagridCellsChangeColor.ViewModel
{
  public class MainViewModel : ViewModelBase
  {
    public MainViewModel()
    {
      ChangeFactor = new DelegateCommand<object>(OnChangeFactor, CanChangeFactor);
    }

    private ObservableCollection<Customer> _customers = Customer.GetSampleCustomerList();
    public ObservableCollection<Customer> Customers
    {
      get
      {
         return _customers;
      }
    }

    public ICommand ChangeFactor { get; set; }
    private void OnChangeFactor(object obj)
    {
      foreach (var customer in Customers)
      {
        if ( customer.Factor != 0 )
        {
          customer.Factor = 0;
        }
        else
        {
          customer.Factor = 1;
        }
      }
    }

    private bool CanChangeFactor(object obj)
    {
      return true;
    }
  }
}

Ecco il modello:

using System;
using System.Collections.ObjectModel;
using DatagridCellsChangeColor.ViewModel;

namespace DatagridCellsChangeColor.Model
{
  public class Customer : ViewModelBase
  {
    public Customer(String first, string middle, String last, int factor)
    {
      this.FirstName = first;
      this.MiddleName = last;
      this.LastName = last;
      this.Factor = factor;
    }

    public String FirstName { get; set; }
    public String MiddleName { get; set; }
    public String LastName { get; set; }

    private int _factor = 0;
    public int Factor
    {
      get { return _factor; }
      set
      {
        _factor = value;
        OnPropertyChanged("Factor");
      }
    }

    public static ObservableCollection<Customer> GetSampleCustomerList()
    {
      return new ObservableCollection<Customer>(new Customer[4]
                               {
                                 new Customer("Larry", "A", "Zero", 0),
                                 new Customer("Bob", "B", "One", 1),
                                 new Customer("Jenny", "C", "Two", 0),
                                 new Customer("Lucy", "D", "THree", 2)
                               });
    }
  }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top