【问题标题】:Binding To Collection Count绑定到集合计数
【发布时间】:2013-03-15 15:22:35
【问题描述】:

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

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

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

    ...

这是我的窗口代码 sn-p:

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

这是我的 MainWindow 的 XAML sn-p:

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

嗯……我做错了什么?

【问题讨论】:

    标签: c# wpf xaml binding


    【解决方案1】:

    您应该在 Counter 上实现 INotifyPropertyChanged,并在修改 m_Collection 时使用 Count 作为属性名称来引发 PropertyChanged

    类似

    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

    【讨论】:

      猜你喜欢
      • 2019-01-06
      • 2011-01-09
      • 2012-06-14
      • 1970-01-01
      • 2018-10-13
      • 2010-11-25
      • 1970-01-01
      • 1970-01-01
      • 2010-12-10
      相关资源
      最近更新 更多