RichTextbox Colored after comparing two column values inside datatemplate in GridView

Deepak Joy Joseph 1 Reputation point
2021-10-07T14:36:59.23+00:00

I have a GridView inside that 2 different column i have a cell template and a datatemplate in that i have the RichTextbox inside that paragraph inside that run and the text property binded on it.



Now i need to compare tow richtexbox text value. If any RichTextbox value is different it need to be highlighted inside thta text Box.

XAML

<GridView Grid.Row="1" x:Name="gfgvBrokenLinks" AutoGenerateColumns="False" ItemsSource="{Binding BrokenLinks}" IsReadOnly="True" AutoExpandGroups="False" RowLoaded="gfgvBrokenLinks_RowLoaded">

<telerik:GridViewDataColumn DataMemberBinding="{Binding Data1}"  Header="Data1" IsGroupable="False">
                        <telerik:GridViewDataColumn.CellTemplate>
                            <DataTemplate>
                                <RichTextBox x:Name="richTextBox2" MinWidth="100" IsReadOnly="True">
                                    <FlowDocument >
                                        <Paragraph>
                                            <Run Text="{Binding Data1,Mode=OneWay}"></Run>
                                        </Paragraph>
                                    </FlowDocument>
                                </RichTextBox>
                            </DataTemplate>
                        </telerik:GridViewDataColumn.CellTemplate>
                    </telerik:GridViewDataColumn>

                    <telerik:GridViewDataColumn DataMemberBinding="{Binding Data2}" Header="{my:LocString ResourceKey=HeaderData2}" IsGroupable="False" >
                        <telerik:GridViewDataColumn.CellTemplate>
                            <DataTemplate>
                                <RichTextBox x:Name="richTextBox3" MinWidth="100" IsReadOnly="True" >
                                    <FlowDocument >
                                        <Paragraph>
                                            <Run Text="{Binding Data2,Mode=OneWay}"></Run>
                                        </Paragraph>
                                    </FlowDocument>
                                </RichTextBox>
                            </DataTemplate>
                        </telerik:GridViewDataColumn.CellTemplate>
                    </telerik:GridViewDataColumn>







c#

private void gfgvBrokenLinks_RowLoaded"object sender, Telerik.Windows.Controls.GridView.RowLoadedEventArgs e)
{



if (e.Row.Cells.Count > 0)
{
RichTextBox rt1 = e.Row?.Cells[8]?.Content as RichTextBox;
RichTextBox rt2 = e.Row?.Cells[9]?.Content as RichTextBox;
if (rt1 != null && rt2 != null)
{
string a1 = StringFromRichTextBox(rt1);
string a2 = StringFromRichTextBox(rt2);
if (!a1.Equals(a2))
{
int startindex = 0;
startindex = a1.Zip(a2, (c1, c2) => c1 == c2).TakeWhile(b => b).Count();
int length = a2.Length - startindex;
Select(rt2, startindex, length, Colors.Yellow);
}



//string text = new TextRange(rt2.Document.ContentStart, rt2.Document.ContentEnd).Text;
//if (text.Length > 0)
//{
// TextPointer myTextPointer1 = rt2.Document.ContentStart.GetPositionAtOffset(startindex + 1);
// TextPointer myTextPointer2 = rt2.Document.ContentEnd;
// if (myTextPointer1 != null && myTextPointer2 != null)
// {
// TextRange tr = new TextRange(myTextPointer1, myTextPointer2);
// tr.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.Yellow);
// }
//}
}
}
}



private static TextPointer GetTextPointAt(TextPointer from, int pos)
{
TextPointer ret = from;
int i = 0;



while ((i < pos) && (ret != null))
{
if ((ret.GetPointerContext(LogicalDirection.Backward) == TextPointerContext.Text) || (ret.GetPointerContext(LogicalDirection.Backward) == TextPointerContext.None))
{
i++;
}



if (ret.GetPositionAtOffset(1, LogicalDirection.Forward) == null)
{
return ret;
}



ret = ret.GetPositionAtOffset(1, LogicalDirection.Forward);
}



return ret;
}



internal string Select(RichTextBox rtb, int offset, int length, Color color)
{
// Get text selection:
TextSelection textRange = rtb.Selection;



// Get text starting point:
TextPointer start = rtb.Document.ContentStart;



// Get begin and end requested:
TextPointer startPos = GetTextPointAt(start, offset);
TextPointer endPos = GetTextPointAt(start, offset + length);



// New selection of text:
textRange.Select(startPos, endPos);



// Apply property to the selection:
textRange.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(color));



// Return selection text:
return rtb.Selection.Text;
}

private string StringFromRichTextBox(RichTextBox rtb)
{
TextRange textRange = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);
return textRange.Text.Replace("\r\n", "");
}

Thanks In Advance

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,815 questions
XAML
XAML
A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
830 questions
{count} votes

3 answers

Sort by: Most helpful
  1. Deepak Joy Joseph 1 Reputation point
    2021-10-08T06:05:18.46+00:00

    I am happy if you can provide an answer to achieve this using only WPF as well.

    Compare two GridView column and highlight the text having difference.

    Thanks in advance

    0 comments No comments

  2. Jack J Jun 24,631 Reputation points Microsoft Vendor
    2021-10-08T08:21:55.697+00:00

    @Deepak Joy Joseph , you could try the following code to highlight the text having difference by comparing two Gridview Column.

    Xaml:

     <ListView ItemsSource="{Binding }" Width="500" Height="200" Name="listview1">  
            <ListView.View>  
                <GridView x:Name="gridiew1" AllowsColumnReorder="true" ColumnHeaderToolTip="Authors">  
                    <GridViewColumn Header="FirstName" Width="120"  >  
                        <GridViewColumn.CellTemplate>  
                            <DataTemplate x:Name="t1">  
                                <RichTextBox x:Name="richTextBox1" MinWidth="200" IsReadOnly="True">  
                                <FlowDocument >  
                                    <Paragraph>  
                                            <Run Text="{Binding FirstName,Mode=OneWay}"></Run>  
                                    </Paragraph>  
                                </FlowDocument>  
                                </RichTextBox>  
                            </DataTemplate>  
                        </GridViewColumn.CellTemplate>  
      
                    </GridViewColumn>  
                    <GridViewColumn Header="LastName" Width="150"  >  
      
                        <GridViewColumn.CellTemplate>  
                            <DataTemplate x:Name="t2">  
                                <RichTextBox x:Name="richTextBox2" MinWidth="100" IsReadOnly="True">  
                                    <FlowDocument >  
                                        <Paragraph>  
                                            <Run Text="{Binding LastName ,Mode=OneWay}"></Run>  
                                        </Paragraph>  
                                    </FlowDocument>  
                                </RichTextBox>  
                            </DataTemplate>  
                        </GridViewColumn.CellTemplate>  
                    </GridViewColumn>  
                </GridView>  
      
            </ListView.View>  
        </ListView>  
    

    C# code:

    public MainWindow()  
            {  
                InitializeComponent();  
                List<Author> authors = new List<Author>();  
                authors.Add(new Author { FirstName = "test111", LastName = "test1" });  
                authors.Add(new Author { FirstName = "test2", LastName = "test2" });  
                authors.Add(new Author { FirstName = "test33", LastName = "test3" });  
                authors.Add(new Author { FirstName = "test4", LastName = "test4" });  
                DataContext = authors;  
            }  
      
            private void Window_Loaded(object sender, RoutedEventArgs e)  
            {  
                for (int i = 0; i < listview1.Items.Count; i++)  
                {  
                    ListViewItem listviewitem = (ListViewItem)listview1.ItemContainerGenerator.ContainerFromIndex(i);  
                    var children = AllChildren(listviewitem);  
                    RichTextBox richTextBox1 = (RichTextBox)children.FirstOrDefault(c => c.Name == "richTextBox1");  
                    RichTextBox richTextBox2 = (RichTextBox)children.FirstOrDefault(c => c.Name == "richTextBox2");  
                    string richText1 = new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd).Text;  
                    string richText2 = new TextRange(richTextBox2.Document.ContentStart, richTextBox2.Document.ContentEnd).Text;  
                    
                    if (richText1!=richText2)  
                    {  
                        richTextBox1.Document.Blocks.Clear();  
                        TextRange tr = new TextRange(richTextBox1.Document.ContentEnd, richTextBox1.Document.ContentEnd);  
                        tr.Text = richText1;  
                        tr.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red);  
                    }  
      
                    Console.WriteLine(richText1);  
                    Console.WriteLine(richText2);  
                }  
                
      
      
            }  
      
            private List<Control> AllChildren(DependencyObject obj)  
            {  
                var list = new List<Control>() { };  
                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)  
                {  
                    var child = VisualTreeHelper.GetChild(obj, i);  
                   if(child is Control)  
                      
                        list.Add(child as Control);  
                        list.AddRange(AllChildren(child));  
                      
                }  
                return list;  
           
            }  
      
    public class Author  
        {  
            public string FirstName { get; set; }  
      
            public string LastName { get; set; }  
      
        }  
    

    Result:

    138729-image.png


    If the response is helpful, please click "Accept Answer" and upvote it.

    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 comments No comments

  3. Deepak Joy Joseph 1 Reputation point
    2021-10-12T05:58:53.967+00:00

    Thank you so much for your answer.
    I have two issues with your answer.
    1.I don't want the gridview to place inside list veiw. Only GridView required.
    Only GridView in xaml.
    2 Highlight only the changes tex not the entire text.

    If possible could you please do the needful for achieving this


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.