Click here to Skip to main content
15,868,016 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a WPF project containing a DataGrid, I fill it with many rows when the program starts, then on each button click I set the content of a cell of it. The problem is if I scroll down and up in the DG, the content of the cells seems to be gone! Please help me identify the problem and what to do to solve it.

The XAML:
XML
<Window x:Class="WpfTest1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <DockPanel Grid.Column="1" Margin="0,10,1,0" Panel.ZIndex="10" MinWidth="437" MinHeight="38" VerticalAlignment="Top" HorizontalAlignment="Right">
            <DataGrid x:Name="DGV" HorizontalAlignment="Stretch" VerticalAlignment="Top" Height="103" Panel.ZIndex="1" RowBackground="#FFC6C6C6" FontWeight="Bold" CanUserSortColumns="False" CanUserResizeColumns="False" CanUserReorderColumns="False" MinColumnWidth="0" IsReadOnly="False" AlternatingRowremoved="Gainsboro"  AlternationCount="2">
                <DataGrid.Columns>
                    <DataGridTextColumn Header=" "/>
                    <DataGridHyperlinkColumn Header="URL" Width="295" Binding="{Binding url}"/>
                    <DataGridTextColumn Header="Ahrefs(http)" Width="79" Binding="{Binding AhrefsHttp}"/>
                    <DataGridTextColumn Header="Ahrefs(www)" Width="83" Binding="{Binding AhrefsWww}"/>
                    <DataGridTextColumn Header="Archive" Width="79" Binding="{Binding Archive}"/>
                    <DataGridTextColumn Header="Majesticseo" Width="79" Binding="{Binding Majesticseo}"/>
                    <DataGridTextColumn Header="Majesticseo(anch historic)" Width="79" Binding="{Binding Majesticseo}"/>
                    <DataGridTextColumn Header="Majesticseo(ref historic)" Width="79" Binding="{Binding Majesticseo}"/>
                </DataGrid.Columns>
            </DataGrid>

        </DockPanel>
        <Button Content="Button" HorizontalAlignment="Left" Margin="0,118,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
    </Grid>
</Window>


And this is the complete code:
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfTest1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        int selectedIndex;

       public class myLink
        {
            private string Url;
            public string url
            {
                get { return Url; }
                set { Url = value; }
            }

            private string ahrefsHttp;
            public string AhrefsHttp
            {
                get { return ahrefsHttp; }
                set { ahrefsHttp = value; }
            }

            private string ahrefsWww;
            public string AhrefsWww
            {
                get { return ahrefsWww; }
                set { ahrefsWww = value; }
            }

            private string archive;
            public string Archive
            {
                get { return archive; }
                set { archive = value; }
            }

            private string majesticseo;
            public string Majesticseo
            {
                get { return majesticseo; }
                set { majesticseo = value; }
            }

            private string majesticseoAnchorHistoric;
            public string MajesticseoAnchorHistoric
            {
                get { return majesticseoAnchorHistoric; }
                set { majesticseoAnchorHistoric = value; }
            }

            private string majesticseoReferringHistoric;
            public string MajesticseoReferringHistoric
            {
                get { return majesticseoReferringHistoric; }
                set { majesticseoReferringHistoric = value; }
            }
        }

       public MainWindow()
       {
           InitializeComponent();

           for (int i = 1; i <= 10; i++)
               AddNewRow("test");
       }

        private void AddNewRow(string txt)
        {
            myLink dm = new myLink { url = txt, AhrefsHttp = "", AhrefsWww = "", Archive = "", Majesticseo = "" };

            DGV.Items.Add(dm);
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            SetLinkStateInDG("Good");
        }

        private void SetLinkStateInDG(string state)
        {

            DGV.SelectedItem = DGV.Items[selectedIndex++];

            if (state != "")
            {
                string cmt = Microsoft.VisualBasic.Interaction.InputBox("Any comment?", "Comment", "", -1, -1);
                if (cmt != "")
                    state = state + " (" + cmt + ")";
            }

            foreach (DataGridCellInfo cellInfo in DGV.SelectedCells)
            {
                // this changes the cell's content not the data item behind it
                if (cellInfo.Column.Header.ToString() == "Majesticseo(anch historic)")
                {
                    DataGridCell gridCell = TryToFindGridCell(DGV, cellInfo);
                    if (gridCell != null) gridCell.Content = state;
                    break;
                }
            }


            DGV.SelectedItem = DGV.Items[selectedIndex];
        }

        static DataGridCell TryToFindGridCell(DataGrid grid, DataGridCellInfo cellInfo)
        {
            DataGridCell result = null;
            DataGridRow row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromItem(cellInfo.Item);
            if (row != null)
            {
                int columnIndex = grid.Columns.IndexOf(cellInfo.Column);
                if (columnIndex > -1)
                {
                    System.Windows.Controls.Primitives.DataGridCellsPresenter presenter = GetVisualChild<System.Windows.Controls.Primitives.DataGridCellsPresenter>(row);
                    result = presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex) as DataGridCell;
                }
            }
            return result;
        }

        static T GetVisualChild<T>(Visual parent) where T : Visual
        {
            T child = default(T);
            int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < numVisuals; i++)
            {
                Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
                child = v as T;
                if (child == null)
                {
                    child = GetVisualChild<T>(v);
                }
                if (child != null)
                {
                    break;
                }
            }
            return child;
        }
    }
}
Posted
Updated 26-Aug-14 9:50am
v2

1 solution

Fixed it!
IT appeared that I have to set a property for the DataGrid to fix it:
XML
ScrollViewer.CanContentScroll="False"
 
Share this answer
 
Comments
vyjesh 9-Mar-24 23:14pm    
Wow this worked, thank you :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900