Explorex
Explorex

Reputation: 577

Add Button to ForEach loop

I have a foreach loop that lists a bunch of websites. I would like the ability to add a button to next to each of these websites.

e.g.

google.com    X  //X represents button
facebook.com  X

I don't think adding a stackpanel is the way to go as I want to add it next to the textblock being created in this for loop.

    public void WebsiteList(string[] blocked_sites)
    {
        Button removewebsite = new Button();
        numofsites = blocked_sites.Length; 
        website.Margin = new Thickness(57, 75, 10, 20);
        website.Width = 300;
        removewebsite.Width = 20;
        removewebsite.Height = 20;
        removewebsite.Foreground = Brushes.Red;
        removewebsite.Content = "X";
        removewebsite.Background = Brushes.Transparent;
        website.Foreground = Brushes.White;
        website.TextWrapping = TextWrapping.Wrap;
        website.FontSize = 13;
        foreach (string Site in blocked_sites)
        {                    
            website.Inlines.Add(new Run("•   "));
            string editedSite = Site.Replace("*://*.", "").Replace("*://*", "").Replace("*://", "").Replace("/*", "");
            website.Inlines.Add(new Run(editedSite));
            website.Inlines.Add(new LineBreak());
            removewebsite.Name = "test";
            //HERE IS WHERE I WANT TO ADD THE BUTTON ON THE END     
        }
    }

I've tried adding a stackpanel using stackpanel.children.Add(removewebsite) but it's not lining up with the textblocks. I think I'm just lacking sufficient knowledge in the most suitable way to go about it, would love to be pointed in the right direction.

Upvotes: 0

Views: 395

Answers (1)

mm8
mm8

Reputation: 169150

Use an ItemsControl and set or bind its ItemsSource property to the modified string[]:

public void WebsiteList(string[] blocked_sites)
{
    numofsites = blocked_sites.Length;
    string[] s = new string[numofsites];
    for (int i = 0; i < numofsites; ++i)
    {
        s[i] = string.Format("•   {0}{1}", blocked_sites[i].Replace("*://*.", "").Replace("*://*", "").Replace("*://", "").Replace("/*", ""),
            Environment.NewLine);
    }
    ic.ItemsSource = s;
}

XAML:

<ItemsControl x:Name="ic">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding}" Foreground="White" TextWrapping="Wrap" FontSize="13" Margin="57, 75, 10, 20" Width="300" />
                <Button Content="X" Foreground="Red" Width="20" Height="30" VerticalAlignment="Center" />
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Upvotes: 1

Related Questions