1

在我的代码隐藏中,我在课堂上有以下内容:

public ObservableCollection<int> ints;

它的值在构造函数中初始化:

ints = new ObservableCollection<int>();

然后我将标签绑定到ints

<Label Name="label" Content="{Binding Source={StaticResource ints}, Path=Count}"/>

运行程序后,XamlParseException出现a:

'在 'System.Windows.StaticResourceExtension' 上提供值引发了异常。' 行号“12”和行位置“20”。

我猜装订线有问题。有什么建议么?

说明该问题的完整演示程序如下:

XAML:

<Window x:Class="BindingObservableCollectionCountLabel.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">

    <DockPanel>            
        <StackPanel>
            <TextBox Name="textBox" Text="10"/>
            <Button Name="add" Click="add_Click" Content="Add"/>
            <Button Name="del" Click="del_Click" Content="Del"/>
            <Label Name="label" Content="{Binding Source={StaticResource ints}, Path=Count}"/>
        </StackPanel>            
    </DockPanel>
</Window>

C#:

using System;
using System.Windows;
using System.Collections.ObjectModel;

namespace BindingObservableCollectionCountLabel
{
    public partial class MainWindow : Window
    {
        public ObservableCollection<int> ints;

        public MainWindow()
        {
            InitializeComponent();

            ints = new ObservableCollection<int>();
        }

        private void add_Click(object sender, RoutedEventArgs e)
        {
            ints.Add(Convert.ToInt32(textBox.Text));
        }

        private void del_Click(object sender, RoutedEventArgs e)
        {
            if (ints.Count > 0) ints.RemoveAt(0);
        }
    }    
}
4

2 回答 2

3

如果不需要在资源中收集该集合,请执行以下操作:

  1. 将绑定更改为

    <Label Name="label"
           Content="{Binding Path=ints.Count,
                             RelativeSource={RelativeSource AncestorType=Window}}"/>
    
  2. 创建ints一个属性:

    public ObservableCollection<int> ints { get; private set; }

如果您需要将此集合作为资源,请将窗口构造函数更改为

public MainWindow()
{
    // line order is important!
    Resources.Add("ints", ints = new ObservableCollection<int>());
    InitializeComponent();
}

并保持 XAML 不变

于 2012-05-11T01:42:27.233 回答
1

您的绑定命令是错误的。

Content="{Binding ints.Count}"
于 2012-05-11T01:41:09.567 回答