在我看来,我有这个:
<TextBlock Text="{Binding Title}"/>
它绑定(bind)到我的 ViewModel 的 Title 属性和 这很简单,效果很好 :
private string _title;
public string Title
{
get
{
return _title;
}
set
{
_title = value;
OnPropertyChanged("Title");
}
}
但是我的 ViewModel 也有属性“FormFields”这是一个包含许多其他用户控件的 StackPanel:
private StackPanel _formFields;
public StackPanel FormFields
{
get
{
return _formFields;
}
set
{
_formFields = value;
OnPropertyChanged("FormFields");
}
}
从我的角度来看,我该如何绑定(bind)?
在 ASP.NET 中有一个 占位符 元素,我正在寻找具有相同功能的东西,例如
伪代码:
<PlaceHolder Content="{Binding FormFields}"/>
最佳答案
首先,不要。与其从 VM 口述 UI,不如口述数据(模型)。换句话说,属性类型应该是 ObservableCollection<FormField>
.然后您的 View 将按如下方式绑定(bind):
<ItemsControl ItemsSource="{Binding FormFields}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
这通常在
.Resources
中定义。父元素的部分。即Window.Resources
或 WrapPanel.Resources
.话虽如此,您可以使用
ContentPresenter
抢StackPanel
并将其粘贴在可视化树中:<ContentPresenter Content="{Binding FormFields}"/>
关于wpf - 如何将 StackPanel 绑定(bind)到我的 ViewModel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/964170/