簡體   English   中英

C#WPF WrapPanel問題

[英]C# WPF WrapPanel Issue

有點難以解釋,但是我有一個WrapPanel,其中包含基於索引i顯示的數據。 索引i取決於用戶是否從ComboBox中選擇了某些內容。 問題是,當用戶從ComboBox中選擇一個新選項時,新的換行/數據與以前的換行/數據重疊。 我希望顯示第一個初始換行,然后在SelectedIndex更改時,應隱藏前一個換行,並基於新索引顯示新換行。 這是一些示例代碼:

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?
}

尚不清楚該代碼的調用方式以及變量colIndex和rowIndex與ComboBox的關系,但是假設i是要更改的變量,似乎問題在於每次ComboBox選擇更改時,內容都基於在第i行上,除了該單元格中已經存在的任何內容(而不是替換它)之外,還將其添加到網格單元中的位置(colIndex,rowIndex)。

修改當前代碼的最簡單方法是在將wrap1添加到網格之前清除網格單元。 例如

更換

tabGrid1.Children.Add(wrap1)

// 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);

不過,這並不是特別優雅,並且動態設置或綁定到TextBlock的內容比每次創建一個新的文本集要好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM