Click here to Skip to main content
16,015,218 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I've the following code. Basically I want to display different rectangles in grid. But with the following code, the rectangles are getting displayed in the same row and column of grid. Can anybody please help me how can I move rectangle to other grid when I do like
C#
test.Add(new DataPoint(Brushes.Black));


XML
<Grid.RowDefinitions>
    <RowDefinition Height="*"/>
    <RowDefinition Height="*"/>
    <RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
    <ColumnDefinition Width="*"/>
    <ColumnDefinition Width="*"/>
    <ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
 
<ListBox Name="list">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Rectangle x:Name="Robot"   Fill="{Binding ColorName}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>


In Code behind:
C#
public class DataPoint
{
  public DataPoint(SolidColorBrush name)
  {
     ColorName = name;
  }

  public SolidColorBrush ColorName { get; set; }
}


C#
public MainWindow()
{
    InitializeComponent();
    List<DataPoint> test = new List<DataPoint>();

    test.Add(new DataPoint(Brushes.Red));
    test.Add(new DataPoint(Brushes.Black));

    list.ItemsSource = test;
}
Posted
Updated 13-Mar-15 3:59am
v2

1 solution

Grid has attached properties Grid.Row and Grid.Column:
https://msdn.microsoft.com/en-us/library/system.windows.controls.grid.row%28v=vs.110%29.aspx[^],
https://msdn.microsoft.com/en-us/library/system.windows.controls.grid.row%28v=vs.110%29.aspx[^].

To move some content UI element from one grid cell to another, you can modify them by calling SetRow and SetColumn methods (static, ones, in this case). This is a very typical way (and even method naming pattern) of changing the "attachment" in the sense of attached property. Please see:
https://msdn.microsoft.com/en-us/library/ms589023(v=vs.110).aspx[^],
https://msdn.microsoft.com/en-us/library/ms589026(v=vs.110).aspx[^].

In you want to understand some background (highly recommended), please see these overview pages:
https://msdn.microsoft.com/en-us/library/ms749011%28v=vs.110%29.aspx[^],
https://msdn.microsoft.com/en-us/library/ms752914%28v=vs.110%29.aspx[^].

—SA
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900