The following code gives the result that we see a divided Grid on 4 elements according to the schedule. Each column is filled with color.
<Grid Grid.Column="1" Background="#FF7E7738">
<Grid Width="Auto">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="0.6*"/>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<Grid Grid.Column="0" Background="Red"></Grid>
<Grid Grid.Column="1" Background="Green"></Grid>
<Grid Grid.Column="2" Background="Blue"></Grid>
<Grid Grid.Column="3" Background="Pink"></Grid>
</Grid>
</Grid>
Below I wrote a code that should do the same.
public ObservableCollection<Grid> ConnectorItemsGridX { get; set; }
public void DrawConnectors()
{
Grid mainGrid = new Grid();
mainGrid.Width = Double.NaN;
ColumnDefinition cd1 = new ColumnDefinition();
cd1.Width = new GridLength(1, GridUnitType.Star);
ColumnDefinition cd2 = new ColumnDefinition();
cd2.Width = new GridLength(1, GridUnitType.Star);
ColumnDefinition cd3 = new ColumnDefinition();
cd3.Width = new GridLength(0.6, GridUnitType.Star);
ColumnDefinition cd4 = new ColumnDefinition();
cd4.Width = new GridLength(1, GridUnitType.Star);
mainGrid.ColumnDefinitions.Add(cd1);
mainGrid.ColumnDefinitions.Add(cd2);
mainGrid.ColumnDefinitions.Add(cd3);
mainGrid.ColumnDefinitions.Add(cd4);
Grid tb1 = new Grid();
tb1.Background = Brushes.Beige;
Grid tb2 = new Grid();
tb2.Background = Brushes.DarkSeaGreen;
Grid tb3 = new Grid();
tb3.Background = Brushes.MistyRose;
Grid tb4 = new Grid();
tb4.Background = Brushes.Violet;
mainGrid.Children.Add(tb1);
mainGrid.Children.Add(tb2);
mainGrid.Children.Add(tb3);
mainGrid.Children.Add(tb4);
Grid.SetColumn(tb1, 0);
Grid.SetColumn(tb2, 1);
Grid.SetColumn(tb3, 2);
Grid.SetColumn(tb4, 3);
ConnectorItemsGridX = new ObservableCollection<Grid>();
ConnectorItemsGridX.Add(mainGrid);
}
Code from the XAMl file to load Grid.
<Grid Grid.Column="1" Background="#FF7E7738">
<ItemsControl ItemsSource="{Binding ConnectorItemsGridX}" HorizontalAlignment="Left">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</Grid>
Why do not I see the result?
It seems to me that such a solution has a problem with downloading the width of the Grid which is higher.
If you type in a fixed value of type mainGrid.Width = 200;
everything is displayed.
The window size may change more dynamically have a width equal to a grid above.
Is there anything I need to include in the code which is not used in the XAML version?