我想将Groupboxes绑定到我的stackpanel。
C#:
internal ObservableCollection<GroupBox> BindingTest
{
get
{
ObservableCollection<GroupBox> collection = new ObservableCollection<GroupBox>();
for (int counter = 0; counter < 5; counter++)
{
GroupBox groupBox = new GroupBox();
groupBox.Header = " ... Header ... ";
groupBox.Content = " ... Content ... ";
collection.Add(groupBox);
}
return collection;
}
}
和xaml代码:
<StackPanel x:Name="Dynamic" Grid.Row="1" Margin="29,118,6,0">
<ItemsControl ItemsSource="{Binding Path=BindingTest}" Height="482">
<ItemsControl.ItemTemplate>
<DataTemplate>
<GroupBox>
<GroupBox.Header>{Binding Path=Header}</GroupBox.Header>
<GroupBox.Content>{Binding Path=Content}</GroupBox.Content>
</GroupBox>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
我的推理错误在哪里?
答案 0 :(得分:1)
在WPF Binding中,您通常不绑定到Controls,只需绑定到对象并让Markup处理UI详细信息。理想情况下,您的对象应实现INotifyPropertyChanged
以通知属性更改的绑定。控件创建已由DataTemplate
处理,它已为您创建GroupBox
并将其属性绑定到绑定中使用的对象的属性。
如果可能,您的ViewModel
不应了解有关用户界面的任何信息,或使用任何控件。 MVVM模式旨在解耦UI和数据/逻辑。
您的数据对象的类可能如下所示:
public class DataObject : INotifyPropertyChanged
{
private string header;
private string content;
public string Header {
get { return header; }
set { header = value; RaisePropertyChanged("Header"); }
}
public string Content {
get { return content; }
set { content= value; RaisePropertyChanged("Content"); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
var handler = PropertyChanged;
if (handler != null) {
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
您绑定的属性也会有所不同:
internal ObservableCollection<DataObject> BindingTest
{
get
{
ObservableCollection<DataObject> collection = new ObservableCollection<DataObject>();
for (int counter = 0; counter < 5; counter++)
{
DataObject item = new DataObject ();
item.Header = " ... Header ... ";
item.Content = " ... Content ... ";
collection.Add(item );
}
return collection;
}
}
我假设创建一个新的集合每次时间访问该属性仅用于测试目的。
答案 1 :(得分:0)
只需将BindingTest
属性更改为public
字段..它会自动将数据绑定到UI ...
基本上,xaml允许您将公共属性绑定到UI,因为我们对内部和私有等其他字段有限制。
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
public ObservableCollection<GroupBox> BindingTest
{
get
{
ObservableCollection<GroupBox> collection = new ObservableCollection<GroupBox>();
for (int counter = 0; counter < 5; counter++)
{
GroupBox groupBox = new GroupBox();
groupBox.Header = " ... Header ... ";
groupBox.Content = " ... Content ... ";
collection.Add(groupBox);
}
return collection;
}
}
}
xaml代码如下
<Grid >
<StackPanel x:Name="Dynamic" >
<ItemsControl ItemsSource="{Binding BindingTest, RelativeSource={RelativeSource AncestorType={x:Type this:MainWindow}}}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<GroupBox Header="{Binding Path=Header}"
Content="{Binding Path=Content}">
</GroupBox>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Grid>