c# - 更新复选框列表
问题描述
我有一个list<Month> months
包含 12 个月对象的名称字符串,其中包含月份名称(例如 januari),以及list<Month> selectedMonths
我想添加到用户使用复选框选择的月份中,并在该框未勾选。
在 XAML 中,我有:
<StackPanel>
<CheckBox IsChecked="{Binding monthCheck}" Content="Januari"/>
<CheckBox IsChecked="{Binding monthCheck}" Content="Februari"/>
[etc...]
<CheckBox IsChecked="{Binding monthCheck}" Content="November"/>
<CheckBox IsChecked="{Binding monthCheck}" Content="December"/>
</StackPanel>
现在在我的视图模型中我有:
private bool _monthCheck;
public bool monthCheck{
get{ return _monthCheck; }
set{
_monthCheck = value;
OnPropertyChanged("maandCheck");
}
现在,如果我单击任何一个复选框,所有 12 个复选框都会随着我单击的一个而改变(可以理解,它们都绑定到同一个 bool);我希望它是当我勾选一个框时,它会Content
选中复选框,并将适当的月份从. 添加months
到selectedMonths
. 我该怎么做?我可以只用monthCheck
setter 中的代码来做到这一点吗?就像是:
set{
_montcheck = value;
if(value){
somehow get Content
select month with name = content from months
selectedMonths.add(thatMonth)
only check the appropriate box
}
if(!value){
somehow get Content
select month with that name
selectedMonths.remove(thatMonth)
only uncheck the appropriate box
}
OnPropertyChanged("maandCheck");
}
不知道我应该怎么做。
解决方案
你的视图模型应该有一个 Month 对象的集合,你的视图中的 ItemsControl 可以绑定到:
<ItemsControl ItemsSource="{Binding Months}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding Name}" IsChecked="{Binding IsSelected}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
视图模型,带有返回所选月份的方法:
public class Month
{
public string Name { get; set; }
public bool IsSelected { get; set; }
}
public class ViewModel
{
public List<Month> Months { get; } = new List<Month>
{
new Month { Name="January" },
new Month { Name="February" },
new Month { Name="March" },
new Month { Name="April" },
new Month { Name="May" },
new Month { Name="June" },
new Month { Name="July" },
new Month { Name="August" },
new Month { Name="September" },
new Month { Name="October" },
new Month { Name="November" },
new Month { Name="December" },
};
public IEnumerable<Month> SelectedMonths
{
get { return Months.Where(m => m.IsSelected); }
}
}
这个例子错过了一个机制,它实际上通知 UI 所选月份集合的变化,但从这个问题来看,不清楚这是否是必需的。
推荐阅读
- html - 使用 react-router-dom 时如何从 css 文件访问公共文件夹中的图像?
- node.js - 如何在 AdonisJs 中使用 HasMany 关系
- sql-server - 如何在 SQL Server 中将 nvarchar 时间戳转换为 datetime2?
- spring-boot - Keycloak:通过用户名或用户ID获取访问令牌
- heroku - 为什么我的 Visual Studio 代码中的某些文件看起来更暗?
- javascript - D3.js 树状图单元格相互重叠
- java - 如何在尝试运行配置时找出文件丢失的原因(在 Java 中设置参数)?
- excel - 用户窗体列表框更改不更新文本框可见性
- webhooks - Webhook 到帐户中的特定组织
- docker - 如何获取正在运行的容器的完整端口详细信息