如何简化C#中通过num值控制对应CheckBox选中状态的switch语句
方案1:最小改动快速简化
不需要修改XAML代码,仅调整后台C#逻辑即可:
- 先在窗口类中声明CheckBox数组,在初始化完成后将所有CheckBox按序号存入数组:
// MainWindow.xaml.cs public partial class MainWindow : Window { // 声明存储所有CheckBox的数组 private CheckBox[] _checkBoxArray; public MainWindow() { InitializeComponent(); // 按序号顺序把CheckBox实例存入数组 _checkBoxArray = new CheckBox[] { checkbox0, checkbox1, checkbox2, checkbox3, checkbox4, checkbox5 }; } }
- 把原来的switch整块替换成如下代码:
// 原来的switch逻辑替换为: if (num >= 0 && num < _checkBoxArray.Length) { _checkBoxArray[num].IsChecked = true; }
方案2:可扩展的MVVM绑定方案
适合后续可能新增CheckBox选项的场景,不用反复修改硬编码的控件名:
- 先创建用于绑定的数据源类:
using System.ComponentModel; using System.Runtime.CompilerServices; public class FileOption : INotifyPropertyChanged { private bool _isSelected; public string FilePath { get; set; } public bool IsSelected { get => _isSelected; set { _isSelected = value; OnPropertyChanged(); } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
- 修改MainWindow的后台代码,声明可观察集合存储所有选项:
using System.Collections.ObjectModel; public partial class MainWindow : Window { public ObservableCollection<FileOption> FileOptions { get; set; } = new ObservableCollection<FileOption> { new FileOption { FilePath = "assets/appfilter.xml" }, new FileOption { FilePath = "xml/appfilter.xml" }, new FileOption { FilePath = "xml/appmap.xml" }, new FileOption { FilePath = "xml/theme__resources.xml" }, new FileOption { FilePath = "xml/drawable.xml" }, new FileOption { FilePath = "values/icon__pack.xml" } }; public MainWindow() { InitializeComponent(); DataContext = this; } }
- 替换原来的XAML中6个CheckBox的代码,改用ItemsControl动态生成:
<ItemsControl ItemsSource="{Binding FileOptions}"> <ItemsControl.ItemTemplate> <DataTemplate> <CheckBox Content="{Binding FilePath}" IsChecked="{Binding IsSelected}"/> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl>
- 原来的switch逻辑替换为:
if (num >= 0 && num < FileOptions.Count) { FileOptions[num].IsSelected = true; }
内容的提问来源于stack exchange,提问作者Hadif Hatta
相关产品推荐
相关产品推荐

