[英]Buttons list bind to Grid into UserControl (WPF, Linq, Buttons)
我正在基於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
作為ItemsPanel
中的ItemsControl
:
<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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.