按钮列表将网格绑定到USERCORTROL(WPF,LINQ,按钮)



我正在根据LINQ查询进行按钮列表。

usercontrol .cs

 public partial class GenerateButtonView : UserControl
 {    
    public GenerateButtonView()
    {
       InitializeComponent();
       List<Button> listOfButtons = new List<Button>();
       for (int x = 0; x <= gb.ListDistinctAutoName().Count; x++)
       {
          Button b = new Button();
          b.Content = "button" + x.ToString();
          listOfButtons.Add(b);               
       }
     }}

generateButtonModel.cs

public class GenerateButtonModel
{
   public List<string> ListDistinctAutoName()
   {
      testViewClassDataContext tv = new testViewClassDataContext();
      List<string> q3 = tv.test_views.Select(i => i.AutoName).Distinct().ToList();               
       return q3;
   }}

如何将按钮的创建列表绑定到我的网格?

usercontrol .xaml

<UserControl.....>
....
        <Grid Grid.Column="1" Grid.Row="3" Grid.ColumnSpan="5" Grid.RowSpan="3">
        </Grid>  
</UserControl>

您应该使用ItemsControl并将其ItemsSource属性绑定到List<Button>

<ItemsControl x:Name="ic" />

public GenerateButtonView()
{
    InitializeComponent();
    List<Button> listOfButtons = new List<Button>();
    for (int x = 0; x <= gb.ListDistinctAutoName().Count; x++)
    {
        Button b = new Button();
        b.Content = "button" + x.ToString();
        listOfButtons.Add(b);
    }
    ic.ItemsSource = listOfButtons;
}}

我的想法是,按钮应在水平上放置,并在其之间的边距

之间放置。

然后,您可以使用StackPanel作为ItemsControlItemsPanel

<ItemsControl x:Name="ic">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal" />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

您设置了每个按钮的Margin属性。

请注意,最好的做法是将ItemsSource属性绑定到数据对象的集合,然后在ItemTemplate中定义实际的UI元素(Button(:

<ItemsControl x:Name="ic">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal" />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Button Content="{Binding}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

您需要手动添加按钮

for (int x = 0; x <= gb.ListDistinctAutoName().Count; x++)
{
    Button b = new Button();
    b.Content = "button" + x.ToString();
    listOfButtons.Add(b);
    grid.Children.Add(b);
}

或使用ItemsControl并将按钮列表设置为ItemsSource

最新更新