【问题标题】:Binding in ItemsControl [duplicate]ItemsControl中的绑定[重复]
【发布时间】: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 = shortcutsItemsControl ItemsSource="{Binding]" 得到相同的结果。

另外,我看到的所有示例在添加项目后的代码中都有ItemSource 赋值!

shortcutsList 工作正常。

【问题讨论】:

  • "注意是 IS EMPTY!!!!!" -- 你可以添加任意数量的感叹号,这并不会改变集合的事实not 为空,如果是,您将永远不会看到该异常。调试代码会让你自己知道发生了什么。
  • 用调试器调试?很高兴您能以何种方式解释它不是空的。我确实知道“Hello World”在那里,但我显然不明白它“算作”来源。我要离开 shortcuts 是空的。

标签: c# wpf data-binding


【解决方案1】:

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

改变

<ItemsControl x:Name="shortcutsItems" Width="100" ItemsSource="{Binding}">
     Hello world

<ItemsControl x:Name="shortcutsItems" Width="100">

【讨论】:

  • 天哪,我恨自己。在插入 Hello World 之前,我确实尝试了几次,但中间的某些东西必须改变,如果它不存在的话,它会起作用。谢谢。
  • 这就是编程的生活哈哈,我们每天都去!很高兴它成功了。
猜你喜欢
  • 2019-09-02
  • 2017-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-09
  • 2015-03-25
  • 2016-06-04
  • 2012-08-23
相关资源
最近更新 更多