简体   繁体   中英

C# WPF WrapPanel Issue

Kind of hard to explain, but I have a WrapPanel that includes data that is displayed based on an index i. The index i changes depending on if the user selects something from a ComboBox. The problem is is when the user chooses a new option from the ComboBox, the new wrap/data overlaps the previous wrap/data. I want the first initial wrap to show, then when the SelectedIndex changes, the previous wrap should be hidden and the new wrap based on the new index to be shown. Here's some sample code:

private void fillColumns(int i, int colIndex, int rowIndex) //Called each time SelectedIndex is changed.
{
    System.Windows.Controls.WrapPanel wrap1 = new System.Windows.Controls.WrapPanel();
    wrap1.Orientation = System.Windows.Controls.Orientation.Vertical;
    wrap1.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
    wrap1.Margin = new Thickness(2, 2, 2, 2);

    System.Windows.Controls.TextBlock courseTextBlock = new System.Windows.Controls.TextBlock();
    courseTextBlock.Inlines.Add(new Run("Course: ") { Foreground = Brushes.Purple, FontWeight = FontWeights.Bold });
    courseTextBlock.Inlines.Add(returnedTable.Tables[0].Rows[i]["course_prefix"].ToString() + " " + returnedTable.Tables[0].Rows[i]["course_num"].ToString());
    courseTextBlock.Margin = new Thickness(2, 2, 2, 2);
    wrap1.Children.Add(courseTextBlock);

    Grid.SetColumn(wrap1, colIndex);
    Grid.SetRow(wrap1, rowIndex);
    tabGrid1.Children.Add(wrap1)
    //Clear WrapPanel after user chooses new ComboBox option?
}

It's a little unclear how this code is called, and how the variables colIndex and rowIndex relate to the ComboBox, but assuming i is the variable that is changing it would seem that the problem is that every time the ComboBox selection is changed, the contents based on row i are added to the grid cell at position (colIndex, rowIndex) in addition to any content already present in that cell rather than replacing it.

The easiest way of modifying your current code would be to clear the grid cell before adding wrap1 to the grid. eg

Replace

tabGrid1.Children.Add(wrap1)

with

// Remove any existing content at this position in the grid
foreach (var existingContent in (from cell in tabGrid1.Children where Grid.GetRow(cell) == rowIndex && Grid.GetColumn(cell) == colIndex select cell).ToArray())
{
    tabGrid1.Children.Remove(existingContent);
}

// add the new content
tabGrid1.Children.Add(wrap1);

This isn't particularly elegant though, and dynamicaly setting or binding to the content of the TextBlock would be preferable to creating a new one each time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM