[英]Buttons list bind to Grid into UserControl (WPF, Linq, Buttons)
I'm doing list of buttons based on Linq query. 我正在基于Linq查询的按钮列表。
UserControl .cs 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 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;
}}
How can I bind the create list of buttons to my Grid? 如何将按钮的创建列表绑定到我的网格?
UserControl .xaml UserControl .xaml
<UserControl.....>
....
<Grid Grid.Column="1" Grid.Row="3" Grid.ColumnSpan="5" Grid.RowSpan="3">
</Grid>
</UserControl>
You should use an ItemsControl
and bind or set its ItemsSource
property to the List<Button>
: 您应该使用
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;
}}
My idea is that buttons should be located horizontally with margin between them
我的想法是,按钮应水平放置,且按钮之间应留有空白
Then you could for example use a StackPanel
as the ItemsPanel
of the ItemsControl
: 然后,你可以例如使用
StackPanel
作为ItemsPanel
中的ItemsControl
:
<ItemsControl x:Name="ic">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
You set the Margin
property of each of the buttons. 您设置每个按钮的
Margin
属性。
Note that the best practice would be to bind the ItemsSource
property to a collection of data objects and then define the actual UI element ( Button
) in the ItemTemplate: 请注意,最佳实践是将
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>
You need to add buttons manually to the grid 您需要手动将按钮添加到网格
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);
}
or use ItemsControl
and set list of buttons as a ItemsSource
或使用
ItemsControl
并将按钮列表设置为ItemsSource
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.