c# binding datagrid wpf

Marco Boscolo 20 Reputation points
2025-01-08T09:39:38.3533333+00:00

Ciao A tutti, ho creato questo codice

namespace WpfApplication6
{
    /// <summary>
    /// Logica di interazione per MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        ObservableCollection<Messaggi> messaggi = new ObservableCollection<Messaggi>();
        
        public MainWindow()
        {
            InitializeComponent();
            dg.ItemsSource = messaggi;
        }
        public class Messaggi
        {
            public int COLOR { get; set; }
            public String ID { get; set; }
            public string Name { get; set; }        
        }
        private void button_Click(object sender, RoutedEventArgs e)    //inserisce stringhe
        {   
            messaggi.Add(new Messaggi() { COLOR = 1, ID = "[001]", Name = "rerer" });
            messaggi.Add(new Messaggi() { COLOR = 1, ID = "[002]", Name = "rerer" });
            messaggi.Add(new Messaggi() { COLOR = 3, ID = "[003]", Name = "gg" });
            messaggi.Add(new Messaggi() { COLOR = 2, ID = "[004]", Name = "rerer" });
        }
        private void ACK_Click(object sender, RoutedEventArgs e)
        {
            for(int i=0;  i<messaggi.Count; i++)
            {
                if (messaggi[i].COLOR == 2)    //se la riga e' verde la cancello
                {
                    messaggi.RemoveAt(i);
                    i--;
                }
                else if (messaggi[i].COLOR == 3) //se la riga e' rosso lampeggiante la faccio diventare rosssa fissa
                {
                    messaggi[i].COLOR = 1;
                }
            }
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            messaggi.Add(new Messaggi() { COLOR = 2, ID = "[004]", Name = "pecora" });
        }
    }

Che interagisce con questo wpf:

<Window x:Class="WpfApplication6.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:WpfApplication6"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid Margin="0,0,0,98">
        <DataGrid x:Name="dg" ItemsSource="{Binding messaggi}" CanUserAddRows="False" AutoGenerateColumns="False" Foreground="White" RowHeight="25" FontSize="16" VerticalContentAlignment="Center" CanUserResizeColumns="False" CanUserResizeRows="False" VerticalGridLinesBrush="{x:Null}">
                <DataGrid.Resources>
                <!-- evita di evidenziare le caselle con il click del mouse-->
                <ResourceDictionary>
                    <Style x:Key="{x:Type DataGridCell}" TargetType="{x:Type DataGridCell}">
                        <Setter Property="Background" Value="{x:Null}" />
                        <Setter Property="BorderBrush" Value="{x:Null}" />
                        <Style.Triggers>
                            <Trigger Property="IsSelected" Value="True">
                                <Setter Property="Background" Value="{x:Null}" />
                                <Setter Property="BorderBrush" Value="{x:Null}" />
                            </Trigger>
                        </Style.Triggers>
                    </Style>
                    <Style TargetType="{x:Type DataGridRow}">
                        <Setter Property="Background" Value="{x:Null}" />
                        <Setter Property="BorderBrush" Value="{x:Null}" />
                        <Style.Triggers>
                            <Trigger Property="IsSelected" Value="True">
                                <Setter Property="Background" Value="{x:Null}" />
                                <Setter Property="BorderBrush" Value="{x:Null}" />
                            </Trigger>
                        </Style.Triggers>
                    </Style>
                </ResourceDictionary>
            </DataGrid.Resources>
            <DataGrid.ColumnHeaderStyle>
                <!-- stile rigadi testa tabella-->
                <Style TargetType="DataGridColumnHeader">
                    <!--<Setter Property="Background" Value="Blue"></Setter>-->
                    <Setter Property="Visibility" Value="Collapsed"></Setter>
                </Style>
            </DataGrid.ColumnHeaderStyle>
            <DataGrid.RowStyle>
                <Style TargetType="DataGridRow">
                    <Setter Property="Background" Value="red"/>
                    <!-- Colore standard righe in assenza di eventi -->
                    <Style.Triggers>
                        <!-- eventi che spedificano il colore di una riga al valore della colonna ID-->
                        <DataTrigger Binding="{Binding COLOR}" Value="1">
                            <Setter Property="Background" Value="Red"></Setter>
                        </DataTrigger>
                        <DataTrigger Binding="{Binding COLOR}" Value="2">
                            <Setter Property="Background" Value="Green"></Setter>
                        </DataTrigger>
                        <DataTrigger Binding="{Binding COLOR}" Value="3">
                            <DataTrigger.EnterActions>
                                <BeginStoryboard>
                                    <Storyboard x:Name="Blink" 
                                    AutoReverse="True" 
                                    RepeatBehavior="Forever">
                                        <ColorAnimationUsingKeyFrames BeginTime="00:00:00"
                                Storyboard.TargetProperty="(Background).(SolidColorBrush.Color)">
                                            <EasingColorKeyFrame KeyTime="00:00:01" 
                                                     Value= "Black" />
                                        </ColorAnimationUsingKeyFrames>
                                    </Storyboard>
                                </BeginStoryboard>
                            </DataTrigger.EnterActions>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </DataGrid.RowStyle>
            <DataGrid.Columns >
                <!-- colonne datagrid -->
                <DataGridTextColumn Header="" Binding="{Binding ID}" Width="50" IsReadOnly="True" />
                <DataGridTextColumn Header="" Binding="{Binding Name}" Width="*" IsReadOnly="True" />
                <DataGridTextColumn Header="" Binding="{Binding Ora}" Width="100" IsReadOnly="True"/>
            </DataGrid.Columns>
        </DataGrid>
        <Button x:Name="button" Content="Button" Margin="68,0,0,-63" Click="button_Click" Height="25" VerticalAlignment="Bottom" HorizontalAlignment="Left" Width="75"/>
        <Button x:Name="ACK" Content="ACK" Margin="0,0,65,-63" Click="ACK_Click" Height="25" VerticalAlignment="Bottom" HorizontalAlignment="Right" Width="75"/>
        <Button x:Name="button_Copy" Content="Button" Margin="220,0,0,-46" Click="button2_Click" Height="25" VerticalAlignment="Bottom" HorizontalAlignment="Left" Width="75"/>
    </Grid>
</Window>

mi servirebbe consiglio per 2 cose:
- se lancio piu' volte button_Click le righe lampeggianti non hanno il lampeggio sincronizzato. e' possibile sincronizzarlo?
 - con evento ACK_Click la lista viene aggiornata, sul datagrid vengono eliminate le righe cancellate in lista ma non cambia il colore delle righe che da lampeggianti devono diventare rosso fisso. qualche consiglio?

grazie 
Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
{count} votes

Answer accepted by question author
  1. Anonymous
    2025-01-09T03:28:58.24+00:00

    Hi, @Marco Boscolo. Welcome to Microsoft Q&A. 

    Use dg.Items.Refresh(); to fix the problem that the color cannot change from flashing to red and the animation cannot be synchronized.

    Adjust your code as follows:

    Picture1


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.