1

私の分離コードでは、クラスに次のものがあります。

public ObservableCollection<int> ints;

その値はコンストラクターで初期化されます。

ints = new ObservableCollection<int>();

次に、ラベルを次のようにバインドしていintsます:

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

プログラムを実行すると、次のことXamlParseExceptionが発生します。

「'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 に答える