c# binding datagrid wpf

Marco Boscolo 0 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 
C#
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.
11,185 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Hongrui Yu-MSFT 3,730 Reputation points Microsoft Vendor
    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.


  2. Jiale Xue - MSFT 48,606 Reputation points Microsoft Vendor
    2025-01-10T09:01:47.49+00:00

    HI @Marco Boscolo. Welcome to Microsoft Q&A. 

    Make sure all rows use the same Storyboard animation asset instead of dynamically creating new animation instances for each row. This way, the animation timeline is managed uniformly, allowing for synchronized flashing.

    <DataGrid.Resources>
        <Storyboard x:Key="BlinkStoryboard" AutoReverse="True" RepeatBehavior="Forever">
            <ColorAnimationUsingKeyFrames BeginTime="00:00:00"
                Storyboard.TargetProperty="(Background).(SolidColorBrush.Color)">
                <EasingColorKeyFrame KeyTime="00:00:00.5" Value="Red" />
                <EasingColorKeyFrame KeyTime="00:01:00" Value="Black" />
            </ColorAnimationUsingKeyFrames>
        </Storyboard>
    </DataGrid.Resources>
    
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="Background" Value="Red"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding COLOR}" Value="3">
                    <DataTrigger.EnterActions>                 
                        <BeginStoryboard Storyboard="{StaticResource BlinkStoryboard}" />
                    </DataTrigger.EnterActions>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.RowStyle>
    
    

    In the button_Click method, you only need to add the row with COLOR=3 to the collection, because all rows with COLOR=3 share the same Storyboard.

    Best Regards,

    Jiale


    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.


  3. Marco Boscolo 0 Reputation points
    2025-01-10T13:30:42.3633333+00:00

    yes:

           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" });
                messaggi.Add(new Messaggi() { COLOR = 3, ID = "[005]", Name = "New Row 1" });
                messaggi.Add(new Messaggi() { COLOR = 3, ID = "[006]", Name = "New Row 2" });
                dg.Items.Refresh();
            }
    

    is correct modify xml in this way?

             <DataGrid.Resources>
                    <!-- evita di evidenziare le caselle con il click del mouse-->
                    <ResourceDictionary>
                        
                        <Storyboard x:Key="BlinkStoryboard" AutoReverse="True" RepeatBehavior="Forever">
                            <ColorAnimationUsingKeyFrames BeginTime="00:00:00"
                Storyboard.TargetProperty="(Background).(SolidColorBrush.Color)">
                                <EasingColorKeyFrame KeyTime="00:00:00.5" Value="Red" />
                                <EasingColorKeyFrame KeyTime="00:01:00" Value="Black" />
                            </ColorAnimationUsingKeyFrames>
                        </Storyboard>
                        
                        <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.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>-->
                            <DataTrigger Binding="{Binding COLOR}" Value="3">
                                <DataTrigger.EnterActions>
                                    <BeginStoryboard Storyboard="{StaticResource BlinkStoryboard}" />
                                </DataTrigger.EnterActions>
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
    
    0 comments No comments

Your answer

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