【发布时间】:2020-07-28 23:58:06
【问题描述】:
在我的一生中,我无法让这个绑定工作。
上面是我的尝试,下面是我在网上找到的一个例子,它有效。
<StackPanel Orientation="Horizontal" Height="100" Width="200" Background="White">
<ItemsControl x:Name="shortcutsItems" Width="100" ItemsSource="{Binding}">
Hello world
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="Normal text"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<ListView x:Name="shortcutsList" Width="100">
<ListView.View>
<GridView x:Name="gridShortcuts">
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
</GridView>
</ListView.View>
</ListView>
</StackPanel>
public partial class ExamShortcuts : UserControl {
public ExamShortcuts() {
InitializeComponent();
ObservableCollection<Shortcut> shortcuts = new ObservableCollection<Shortcut>();
shortcuts = new ObservableCollection<Shortcut>();
shortcutsList.ItemsSource = shortcuts;
shortcutsItems.ItemsSource = shortcuts; // ERROR!!!
//shortcuts.Add(new Shortcut() { Name = "Shortcut Exam 1" });
//shortcuts.Add(new Shortcut() { Name = "Shortcut Exam 2" });
}
}
public class Shortcut {
public string Name { get; set; }
}
当我运行时,它对shortcutsItems.ItemsSource = shortcuts; 显示“使用 ItemsSource 之前项目集合必须为空”
请注意,它是空的!!!!!!!当然,当 Add 行未注释时,它也不起作用。
我试过使用DataContext = shortcuts 和ItemsControl ItemsSource="{Binding]" 得到相同的结果。
另外,我看到的所有示例在添加项目后的代码中都有ItemSource 赋值!
shortcutsList 工作正常。
【问题讨论】:
-
"注意是 IS EMPTY!!!!!" -- 你可以添加任意数量的感叹号,这并不会改变集合的事实not 为空,如果是,您将永远不会看到该异常。调试代码会让你自己知道发生了什么。
-
用调试器调试?很高兴您能以何种方式解释它不是空的。我确实知道“Hello World”在那里,但我显然不明白它“算作”来源。我要离开
shortcuts是空的。
标签: c# wpf data-binding