将按钮添加到ForEach循环

时间:2019-02-18 01:45:09

标签: c# wpf

我有一个foreach循环,其中列出了一堆网站。我希望能够在每个网站旁边添加一个按钮。

例如

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

我不认为添加堆栈面板是一种方法,因为我想将其添加到在此for循环中创建的文本块旁边。

    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     
        }
    }

我尝试使用stackpanel.children.Add(removewebsite)添加一个堆栈面板,但是它与文本块没有对齐。我想我只是以最合适的方式缺乏足够的知识来解决这个问题,因此很乐意指出正确的方向。

1 个答案:

答案 0 :(得分:1)

使用ItemsControl并将其ItemsSource属性设置或绑定到修改后的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>