绑定到收集计数

时间:2013-03-25 23:33:00

标签: c# wpf xaml binding

我正在尝试创建一个小按钮,通过绑定显示自定义类的实际Count属性。这是我的自定义类代码段:

public sealed class Counter : IEnumerable<MyClass>
{
    private List<MyClass> m_Collection;

    public Int32 Count
    {
        get { return m_Collection.Count; }
    }

    ...

这是我的Window代码片段:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        m_Counter = new Counter();
    }

以下是我的MainWindow的XAML片段:

<Window ... DataContext="{Binding RelativeSource={RelativeSource Self}}">
...
   <Button Content="{Binding Path=m_Counter.Count}" Height="40" Width="40"/>

......我做错了什么?

1 个答案:

答案 0 :(得分:4)

您应该在计数器上实施INotifyPropertyChanged,并在修改PropertyChanged

时将m_Collection计数作为属性名称加注

这样的东西
public sealed class Counter : IEnumerable<MyClass> , INotifyPropertyChanged
{
    private List<MyClass> m_Collection;

    public Int32 Count
    {
        get { return m_Collection.Count; }
    }

    public void Add(MyClass item)
    {
        m_Collection.Add(item);
        if (PropertyChanged != null)
            PropertyChanged(null, new PropertyChangedEventArgs("Count"));
    }

public event PropertyChangedEventHandler PropertyChanged;

您可能必须为所有List突变事件触发它。

更简单的事情就是做

之类的事情
 public sealed class Counter2 : IEnumerable<MyClass>
    {
        private ObservableCollection<MyClass> m_Collection = new ObservableCollection<MyClass>();

        public ObservableCollection<MyClass> Collection
        {
            get
            {
                return m_Collection;
            }
        }

    }

并在XAML中绑定到Collection.Count