【问题标题】:Operation is not valid while ItemsSource is in use exception - what am I doing wrong?当 ItemsSource 正在使用异常时,操作无效 - 我做错了什么?
【发布时间】:2012-06-13 21:24:17
【问题描述】:

我正在尝试将 2d 对象列表链接到内容控件。我遇到了一个我不明白的例外。有人可以为我澄清一下吗? (我尝试将 C# 中的 first.ItemsSource 属性设置为我在代码中声明的 NationMetrics 对象 - 它给了我同样的异常)

外部异常:

向“System.Windows.Controls.ItemCollection”类型的集合添加值引发异常。

内部异常:

使用 ItemsSource 时操作无效。改为使用 ItemsControl.ItemsSource 访问和修改元素。

NationMetrics 类:

public class NationMetrics
{
     List<List<Field>> _Nations = new List<List<Field>>();

     public List<List<Field>> Nations { get { return _Nations; } set { _Nations = value; } }

}

这是触发异常的 MainWindow.xaml 中的 sn-p

<Grid>
    <ItemsControl x:Name="first" ItemTemplate="{DynamicResource DataTemplate_Level1}" ItemsSource="{Binding Path=Nations, Source={StaticResource nationMetric}}" />
</Grid>

这是我的 Window.Resources 中定义国家指标的 sn-p

<local:NationMetrics x:Name="nm" x:Key="nationMetric" />

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:

    你可以试试这样的:

    <Window.Resources>
        <DataTemplate x:Key="inner">
                        <TextBlock Content="{Binding}"/>
        </DataTemplate>
    
    <DataTemplate x:Key="outer">
        <ItemsControl ItemsSource="{Binding}" ItemTemplate="{DynamicResource inner}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        </ItemsControl>
    </DataTemplate>
    
    </Window.Resources>
    
    <ItemsControl x:Name="itemControl" ItemsSource="{Binding Path=Nations, Source={StaticResource nationMetric}}" ItemTemplate="{DynamicResource outer}">
    

    这基本上表明列表中有一个列表并进行适当的绑定。我没有尝试过,但我认为这是方法!

    其他资源:

    WPF: How to create a custom items control panel?

    Binding 2 dimensional Collection to some control

    【讨论】:

    • 嗯...我原来的 xaml 模板是 &lt;DataTemplate x:Key="DataTemplate_Level1"&gt; &lt;ItemsControl ItemsSource="{Binding}" ItemTemplate="{DynamicResource DataTemplate_Level2}"&gt; &lt;ItemsPanelTemplate&gt; &lt;StackPanel Orientation="Horizontal"/&gt; &lt;/ItemsPanelTemplate&gt; &lt;/ItemsControl&gt; &lt;/DataTemplate&gt; &lt;DataTemplate x:Key="DataTemplate_Level2"&gt; &lt;TextBlock Text="{Binding}" /&gt; &lt;/DataTemplate&gt; 你的工作 - 内部必须在外部之前声明吗?
    • XAML、HTML、CSS 等都是命令式/声明式语言。这意味着代码是从上到下读取的,并且更改的变量不会影响其他因变量。所以是的,这意味着声明资源的顺序会影响最终结果。有关声明式编程语言的更多信息:en.wikipedia.org/wiki/Declarative_programming。我很高兴它成功了! :)
    猜你喜欢
    • 2018-09-22
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    • 2012-04-15
    • 2014-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多