繁体   English   中英

问题绑定 .IsSelected 复选框计数到标签 WPF

[英]Problem binding .IsSelected count of checkbox to Label WPF

我是新的 WPF,仍在尝试了解 MVVM 绑定。

基本上我试图绑定 listofitems.Where(x => x.IsSelected == true).Count(); 到一个标签,其中 IsSelected 代表复选框检查。 每次取消选中复选框时,标签也会更新。

IsSelected 是 Item 类的一个属性

XML

<Label x:Name="numeratorLbl" Content="{Binding Path=ItemList, Mode=TwoWay}" />

Code Behind

        private bool mIsSelected;
        public bool IsSelected
        {
            get { return mIsSelected;  }
            set
            {
                mIsSelected = value;
                OnPropertyChanged("IsSelected");  
            }
        }
        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

public ObservableCollection<Item> listofitems = new ObservableCollection<Item>();



谁能帮我吗?

创建一个单独的属性,它接受状态并根据需要的任何/所有逻辑或输出文本返回正确的文本。

使用其他属性对上述属性进行通知更改。 例如,每次更改IsSelected ,它也会更改我们的新属性LabelStatus的状态。 对所有其他与逻辑相关的设置属性执行此操作

public bool IsSelected
{
    get { return mIsSelected;  }
    set
    {
        mIsSelected = value;
        OnPropertyChanged("IsSelected"); 
        OnPropertyChanged("LabelStatus"); 
    }
}

public string LabelStatus 
{ 
    get { return IsSelected? listofitems.Where( ... ).Count() : "-"; } 
}

然后像Content="{Binding LabelStatus}" />一样绑定到LabelStatus


我在我的博客上提供了一个更完整的例子:

Xaml:用于更轻松绑定的 MVVM 示例

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM