C# 将StackPanel子级绑定到ObservableCollection
我有一个可观察的按钮集合:C# 将StackPanel子级绑定到ObservableCollection,c#,wpf,xaml,binding,stackpanel,C#,Wpf,Xaml,Binding,Stackpanel,我有一个可观察的按钮集合: public partial class MainWindow : Window { public ObservableCollection<Button> myBtCollection { get; set; } public MainWindow() { InitializeComponent(); myBtCollection = ne
public partial class MainWindow : Window
{
public ObservableCollection<Button> myBtCollection { get; set; }
public MainWindow()
{
InitializeComponent();
myBtCollection = new ObservableCollection<Button>();
Button bot1 = new Button { Width = 200, Height = 25, Content = "Boton 1" };
Button bot2 = new Button { Width = 150, Height = 50, Content = "Boton 2" };
Button bot3 = new Button { Width = 100, Height = 100, Content = "Boton 3" };
myBtCollection.Add(bot1);
myBtCollection.Add(bot2);
myBtCollection.Add(bot3);
myBtCollection.Add(bot1);
myBtCollection.Add(bot3);
myBtCollection.Add(bot2);
myBtCollection.Add(bot1);
}
}
公共部分类主窗口:窗口
{
公共ObservableCollection myBtCollection{get;set;}
公共主窗口()
{
初始化组件();
myBtCollection=新的ObservableCollection();
按钮bot1=新按钮{Width=200,Height=25,Content=“Boton 1”};
按钮bot2=新按钮{宽度=150,高度=50,内容=“Boton 2”};
按钮bot3=新按钮{Width=100,Height=100,Content=“Boton 3”};
myBtCollection.Add(bot1);
myBtCollection.Add(bot2);
myBtCollection.Add(bot3);
myBtCollection.Add(bot1);
myBtCollection.Add(bot3);
myBtCollection.Add(bot2);
myBtCollection.Add(bot1);
}
}
我想将该集合绑定到我的StackPanel(在本例中,它是一个常量集合,但最终将是可变的)。这是我的XAML:
<Window x:Name="mainWindow" x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel x:Name="stack">
</StackPanel>
<ItemsControl Width="Auto"
Height="Auto"
ItemsSource="{Binding ElementName=mainWindow, Path=myBtCollection}">
</ItemsControl>
</Grid>
</Window>
我读过,它可以通过使用ItemsControl来实现,但我不知道如何完成它。(是否需要在代码隐藏中设置DataContext?)
<ItemsControl.Style>
<Style TargetType="{x:Type ItemsControl}">
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
</Style>
</ItemsControl.Style>
我同意@inxs的评论。但要使此工作在创建myBtCollection后移动
InitializeComponent()
public MainWindow()
{
myBtCollection = new ObservableCollection<Button>();
...
InitializeComponent();
}
public主窗口()
{
myBtCollection=新的ObservableCollection();
...
初始化组件();
}
或者为
myBtCollection
实现为什么要将控件绑定到控件?MVVM的意义是绑定数据并让它在您的控件中表示。你想实现什么?我已经创建了一个UserControl表单(一个文本框和一个按钮),它将被创建多次。我想把它放在我的主窗口是个好主意。昨天我试着学习MVVM,但是这个概念对我来说太难了,所以我走了很容易(而且很长)的路。它成功了!谢谢但仅显示最后3个按钮,我尝试将窗口大小增大(900x900像素),但没有成功。创建3个以上的按钮,您将看到更多。:)为什么我不能代表整个系列?似乎它只显示不同的项目。@Sturm您只有三个按钮。将它们多次添加到集合中不会改变这一事实。