我是 wpf 的初学者,我遇到了 stackpanel 绑定的问题。我必须动态生成标签,并将其添加到堆栈面板。我在 .cs 文件中有以下代码:
public DataImport()
{
labels.Add(new StringObject { Value = "tes" });
labels.Add(new StringObject { Value = "tes2" });
labels.Add(new StringObject { Value = "tes3" });
}
private ObservableCollection<StringObject> labels = new ObservableCollection<StringObject>();
public ObservableCollection<StringObject> Labels
{
get { return labels; }
private set
{
if (value == labels) return;
labels = value;
OnPropertyChanged("Labels");
}
}
public class StringObject
{
public string Value { get; set; }
}
接下来在 xaml 我有:
<ItemsControl ItemsSource="{Binding Path=Labels}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Grid.Row="1" Height="237" HorizontalAlignment="Center" VerticalAlignment="Top" Width="186" FlowDirection="LeftToRight">
<Label Content="{Binding Path=Value}"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
真正的问题是,在 xaml 窗口中,我只看到标签对象中的第一个元素。你能告诉我我做错了什么吗?
PS:我的类DataImport当然继承了INotifyPropertyChanged