在 ItemsControl 中的绑定

35 浏览
0 Comments

在 ItemsControl 中的绑定

此问题已有答案:

\"使用ItemsSource之前必须清空项目集合。\"

我想不出如何使此数据绑定功能正常工作。

上方是我的尝试,下面是我在网上找到的可行示例。

    
        
            Hello world
            
                
                    
                        
                        
                    
                
            
        
        
            
                
                    
                
            
        
    

    public partial class ExamShortcuts : UserControl {
        public ExamShortcuts() {
            InitializeComponent();
            ObservableCollection shortcuts = new ObservableCollection();
            shortcuts = new ObservableCollection();
            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 = shortcutsItemsControl ItemsSource=\"{Binding}\",但结果相同。

此外,我看到的所有例子中,ItemSource的赋值都是在添加项目之后的代码中完成的!

shortcutsList正常工作。

admin 更改状态以发布 2023年5月21日
0
0 Comments

在设置ItemsSource之前,先删除“Hello World”和ItemSource绑定部分。你试图动态设置,但是已经在xaml中设置了它,这就是它认为源不为空的原因。我打赌这就是导致你问题的原因。


     Hello world

改为


0