![](/img/trans.png)
[英]Binding a StackPanel of custom user controls to an ObservableCollection of custom classes
[英]Binding StackPanel Children to an ObservableCollection
我有一个ObservableCollection按钮:
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);
}
}
我想将该集合绑定到我的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吗?)
我同意@inxs的评论。 但是为了使这项工作在创建myBtCollection之后移动InitializeComponent()
public MainWindow()
{
myBtCollection = new ObservableCollection<Button>();
...
InitializeComponent();
}
或者为myBtCollection
实现INotifyPropertyChanged 。
如果您希望使用其他Panel或更改StackPanels方向,可以使用ItemsControl上的Property“ItemsPanel”并将其设置如下:
<ItemsControl.Style>
<Style TargetType="{x:Type ItemsControl}">
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
</Style>
</ItemsControl.Style>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.