我正在根据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
作为ItemsControl
的ItemsPanel
:
<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