I have more than 20 checkboxes in my wpf form. I need store IsChecked
values from all of 开发者_StackOverflowthem in some object.
I know two ways.
1) bind all checkboxes to corresponding properties in object using dependency property like here
2) handle Clicked
event of all of them
Which solution is better? Is there a better solution taking up less space in code-behind?
Definitely use a Binding
If your CheckBoxes are unrelated and are all over the place, you'll need 20 different dependency properties to bind to in your DataContext or ViewModel
If your CheckBoxes are all together, such as listed one after another or in a Grid, you can put them in a collection and bind an ItemsControl
to them
<ItemsControl ItemsSource="{Binding Options}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding Description}"
IsChecked="{Binding IsChecked}" />
</DataTemplate>
</ItemsControl>
</ItemsControl>
Your ViewModel or DataContext would contain something like this:
private List<Option> options;
private List<Option> Options
{
get
{
if (options== null)
{
options = new List<Option>();
// Load Options - For example:
options.Add(new Option { Description = "Option A", IsChecked = false });
options.Add(new Option { Description = "Option B" });
options.Add(new Option { Description = "Option C", IsChecked = true});
}
return options;
}
}
And your Option
class would simply be
public class Option
{
public string Description { get; set; }
public bool IsChecked { get; set; }
}
Binding.
The reason is simple. If you decided to hook up to the IsChecked event you would have to have extra code to figure out which property to which check box.
Worse case is you have a method for each.
With binding once you set it to the checkbox you are done. All you have to do is save the object at the end.
If you use a good MVVM framework you can use binding without having to do them by hand(only name them to some convention) - I like Caliburn Micro but there are a lot of good ones out there.
To store IsChecked state I would suggest to follow the first one (using binding
), it is better because binding allows keep UI and code behind more clean and decoupled.
Second one (handling an event
) is most like WinForms approach so I do not see why you should follow it in WPF Application.
EDIT: Answer to question regarding multiple properties
If depends on what actually is bound to a View and how check boxes are placed in the View.
If you're using some ItemsControl
container like ListView
and each check box belong to single row/column - you can bind all checkboxes to a single collection like
private IList<bool> states;
public IList<bool> States
{
get
{
return this.states;
}
set
{
this.states = value;
this.OnPropertyChanged("States");
}
}
To give you a concrete answer - share please UI layout of Form where checkboxes are placed.
精彩评论