C# wpf Datagrid с AutoGenerateColumns и Cellbackground - PullRequest
1 голос
/ 06 января 2020

У меня есть WPF-приложение с DataGrid, которое подключается к разным .ItemsSource, создает столбцы, работает нормально.

В большинстве случаев первый столбец имеет некоторый идентификатор для запроса к серверу. данные. Я хочу раскрасить некоторые ячейки каждой строки разными цветами в зависимости от этих внутренних данных.

Проблема: мой IValueConverter не доставляет строку, в которой я нахожусь. Поэтому в рамках события окрашивания ячейки я получаю содержимое этого ячейка, но я не нашел способа получить доступ к идентификатору в первом столбце этой строки ...

Все, что подталкивает меня в правильном направлении, будет оценено.

Я подготовил некоторый рабочий демонстрационный код, можно скопировать / вставить в новое wpf-приложение:

XAML

<Window x:Class="Datagridtest.MainWindow"
        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:local="clr-namespace:Datagridtest"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <DataGrid x:Name="dgrid" HorizontalAlignment="Left" Height="255" Margin="98,74,0,0" VerticalAlignment="Top" Width="615"/>
    </Grid>
</Window>

.cs Код

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;

namespace Datagridtest
{
    public class Data
    {
        public string id { get; set; }
        public string name { get; set; }
        public string location { get; set; }
    }

    public class DataConti
    {
        public List<Data> daten = new List<Data>();
        public void MakeDummy()
        {
            var rand = new Random();
            for (int i = 0; i < 20; i++)
            {
                Data d = new Data
                {
                    name = "egal" + i.ToString(),
                    location = "egal" + i.ToString()
                };

                d.id = rand.Next(1000).ToString();
                daten.Add(d);
            }
        }
    }

    class ValueConverterConti
    {
        public DataConti conti { get; set; }
        public DataGridColumn col { get; set; }
    }

    class VC : IValueConverter // IMultiValueConverter?
    {
        public object Convert(object value, Type targetType,
                               object parameter, CultureInfo culture)
        {
            ValueConverterConti c = (ValueConverterConti)parameter;
            SolidColorBrush sb = Brushes.White;

            if (c.col.DisplayIndex == 1)
            {
                // all with id%3==0--> Blue
                sb = Brushes.LightBlue;
            }
            else
            if (c.col.DisplayIndex == 2)
            {
                // all with id%2==0--> Yellow
                sb = Brushes.Yellow;
            }

            return sb;
        }

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

    public partial class MainWindow : Window
    {
        DataConti dataconti = new DataConti();

        void DataGridAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            VC vc = new VC()
            {
                // ?
            };

            ValueConverterConti dc = new ValueConverterConti
            {
                col = e.Column,
                conti = dataconti
            };

            Style style = new Style(typeof(DataGridCell));
            style.Setters.Add(new Setter(DataGridCell.BackgroundProperty,
                       new Binding(e.PropertyName)
                       {
                           Converter = vc,
                           ConverterParameter = dc
                       }));
            e.Column.CellStyle = style;
        }

        public MainWindow()
        {
            InitializeComponent();
            dataconti.MakeDummy();

            dgrid.AutoGenerateColumns = true;
            dgrid.AutoGeneratingColumn += DataGridAutoGeneratingColumn;

            dgrid.ItemsSource = dataconti.daten;
        }
    }
}

1 Ответ

0 голосов
/ 08 января 2020

Таким образом, решение этой проблемы - использование MultiBinding.

    public class QuantityToBackgroundConverterM : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            SolidColorBrush sb = Brushes.White;
            try
            {
                if (values[0] != DependencyProperty.UnsetValue)
                {
                    int i = System.Convert.ToInt32(values[0]);
                    string column = (string)values[1];

                    switch (column)
                    {
                        case "name":
                            if (i % 2 == 0) { sb = Brushes.LightBlue; }
                            break;
                        case "location":
                            if (i % 3 == 0) { sb = Brushes.Yellow; }
                            break;
                    }
                }
            }
            catch (Exception){}

            return sb;
        }

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

    public partial class MainWindow : Window
    {
        DataConti dataconti = new DataConti();

        void DataGridAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            Binding bid = new Binding();
            bid.Path = new PropertyPath("id");
            Binding bheadername = new Binding();
            bheadername.Source = e.Column.Header as String;
            Binding bcolumn = new Binding();
            bcolumn.Path = new PropertyPath(e.Column.Header as String);

            MultiBinding binder = new MultiBinding();
            binder.Bindings.Add(bid);
            binder.Bindings.Add(bheadername);
            binder.Bindings.Add(bcolumn);
            binder.Converter = new QuantityToBackgroundConverterM();

            Setter setter = new Setter(DataGridRow.BackgroundProperty, binder);
            Style style = new Style(typeof(DataGridCell));
            style.Setters.Add(setter);

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