[英]Set Dynamic Size of WPF-Object in Code Behind
我目前正在嘗試設計如下所示的條形圖:每行的行數和條形數可能會根據我的圖表所依賴的dataTable而有所不同。 (間隙不是故意的,但不是我的問題自動取款機)
我正在嘗試通過網格實現我的BarChart。 我的數據表為我提供了一個鍵,一個長度,一個名稱和一個父項(這是右側欄的鍵,因為每一行都將右側欄拆分成較小的欄)。
網格大小當前基於我的maingrid,在XAML-ViewModel中將其設置為900 * 400。 我的小節當前設置為它們的Length / MaxLength * GridLength(而第一個小節始終為MaxLength)並具有邊距,因為我希望它們從右向左移動。 我的問題是,我想使該網格的尺寸動態變化,但是如果我沒有為MainGrid設置固定尺寸,則Grid的尺寸將為NaN或0。
我刪除了一些令人困惑的部分,但是基本上這是我后面的代碼:
public MainWindow()
{
InitializeComponent();
myTable = new DataTable();
}
InitChart(DataTable dt) //Is called from another class when the DataTable changes
{
Maingrid.Children.Clear(); //Dispose old BarChart
myTable = dt;
Grid grid1 = new Grid();
grid1.Width = MainGrid.Width;
grid1.Height = MainGrid.Height;
// Create Rows
int Pa = -1;
foreach (DataRow rw in myTable.Rows)
{
if (Pa != (int)rw["Parent"])
{
RowDefinition rdef = new RowDefinition();
rdef.Height = new GridLength(20);
grid.RowDefinitions.Add(rdef);
}
Pa = (int)rw["Parent"];
}
foreach (DataRow row in myTable.Rows)
{
int P = (int)row["Parent"];
foreach (DataRow rw in myTable.Rows)
{
if ((int)rw["Parent"] == P) //Each row splits the right bar of the previous row, all bars in one row have the previous split bar as their Parent. I draw all Bars with the same Parent in one Row.
{
if ((int)rw["Val"] != 0) //Some Bars are disabled or 0. I don't draw them
{
Rectangle rect = new Rectangle();
double L = rw["Val"]; //The Value of one Bar
rect.Width = L / nMaxValue * grid.Width; //Calculate width of my Rectange based on the maximal value one bar can have
rect.Height = 20; //Just a height
rect.Margin = new Thickness( grid.Width - nRowValue/nMaxValue * grid.Width, 0, 0, 0); //Margin to display the bars next to each other
rect.Fill = Col;
rect.HorizontalAlignment = HorizontalAlignment.Left; //Although i want to have my BarChart go from right to left, I align all bars from on the left and then move them with my margin
Grid.SetRow(rect, y);
nRowValue = nRowValue - (int)rw["Val"];
grid1.Children.Add(rect);
}
}
}
}
MainGrid.Children.Add(grid1);
}
XAML:
<UserControl x:Class="WpfApp.MainWindow"
<Grid x:Name="MainGrid" Background="#f0f0f0" Height="400" Width="900" />
</UserControl>
我也已經嘗試過使用ItemsControl,但似乎無法正常工作。
要使調整大小動態化,可以使用“網格”和“網格列”。 網格是一種出色的布局控件,因為它可以使用所有可用空間。 只需確保不要在任何時候設置其寬度即可。 這樣,外部控件(如Page或Window)可以控制它使用多少空間。
過程:
maxLength
值。 將那么多網格列添加到網格中。 確保不設置列寬。 以下代碼與添加* -column相同,這是我們需要的:
for (int i = 0; i < maxLength; i++) { MyGrid.ColumnDefinitions.Add(new ColumnDefinition()); }
對於每個條,創建矩形,但不要設置其寬度或邊距。 而是設置Column和ColumnSpan。 例如:
var rectangle = new Rectangle { Fill = new SolidColorBrush(Colors.LightGray), Opacity = 0.5, Margin = new Thickness(0, -10, 0, 0), Height = 66 }; MyGrid.SetColumn(rectangle, (int)maxLength - data.Length); MyGrid.SetColumnSpan(rectangle, data.Length);
希望這可以幫助。 如果您遇到任何問題,請告訴我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.