StackPanel 找不到ItemsSource
时间: 2023-08-24 18:04:03 浏览: 50
如果 StackPanel 找不到 ItemsSource 属性,可能是因为它不是一个 ItemsControl。StackPanel 只是一个简单的布局控件,它不能直接绑定数据。如果你想动态添加控件,可以使用 ItemsControl 或 ListBox 这样的 ItemsControl 类型来实现。
以下是一个简单的例子:
1. 在ViewModel中声明一个ObservableCollection类型的数据
```
public ObservableCollection<Control> Controls {get;set;}
```
2. 在View中使用 ItemsControl 控件,并绑定ObservableCollection到 ItemsSource 上
```
<ItemsControl ItemsSource="{Binding Controls}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<!-- 这里是控件的模板 -->
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
```
3. 当需要添加控件时,向ObservableCollection中添加新的数据
```
Controls.Add(new Button(){Content="New Button"});
```
这样就可以实现动态往 ItemsControl 中添加控件了。注意,你需要在 ItemsControl 的 ItemTemplate 中定义控件的模板,这样控件才能正确地显示。