Search code examples
wpfstackpanel

add spacing between stack element code behind


I did xml parsing and created checkboxes in a stack panel. How do i add spacing between the children elements of the stack panel? They seems to be stacking on each other without proper spacing and I wish to do it in the code behind (.cs file).

Many thanks.

EDIT 1: Sorry forgot to add my codes:

my XAML:

<TabItem Header ="XML PARSING" Name="Tabitem5" Visibility="Visible">
        <StackPanel Name="stack1" >
            <Button Height="23" Name="XmlappendButton" Width="75" HorizontalAlignment="Right" Click="XmlappendButton_Click">Update</Button>
        </StackPanel>

</TabItem>

my code behind:

private void xmlparsing()
{
    XDocument xmlDoc = XDocument.Load(@"C:\Build.xml");
    var abc = from target in xmlDoc.Descendants("target")
              select (string)target.Attribute("if");

    foreach(string target in abc)
    {
        if (target != null && !Dictionarycheck.ContainsKey(target))
        {
            System.Windows.Controls.CheckBox chk = new System.Windows.Controls.CheckBox();
            chk.Name = target+"CheckBox";
            chk.Content = target;
            chk.Tag = target;
            stack1.Children.Add(chk);
        }
    }       
}

Solution

  • Give margin to the child elements you are creating

    _chk.Margin = new Thickness(0,100,0,0); 
    

    But ideally would be good this in XAML. Bind your XML data as a collection to a ListBox and provide proper DataTemplate with a CheckBox in it. The proper WPF way of doing this would be as follows. XAML

      <ListBox x:Name="lstBox">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <CheckBox Content="{Binding}" Tag="{Binding}"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    

    Code Behind

    XDocument xmlDoc = XDocument.Load(@"C:\Build.xml");    
    lstBox.ItemsSource = from target in xmlDoc.Descendants("target") select (string)target.Attribute("if");