在我的代码隐藏中,我在课堂上有以下内容:
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);
}
}
}
答案 0 :(得分:2)
如果不要求在资源中拥有该集合,请执行以下操作:
更改绑定到
<Label Name="label"
Content="{Binding Path=ints.Count,
RelativeSource={RelativeSource AncestorType=Window}}"/>
将ints
设为属性:
public ObservableCollection<int> ints { get; private set; }
如果您需要此集合作为资源,请将窗口构造函数更改为
public MainWindow()
{
// line order is important!
Resources.Add("ints", ints = new ObservableCollection<int>());
InitializeComponent();
}
并保持XAML不变
答案 1 :(得分:1)
您的绑定命令错误。
Content="{Binding ints.Count}"