I'm converting a program from WinForms to WPF. There seems to be a lot of unnecessary syntax changes. But the one I'm having trouble with is saving the "checked" or "unchecked" status to Properties.Settings. In WinForms I used:
private void chkBackup_CheckedChanged(object sender, EventArgs e)
{
Properties.Settings.Default.Backup = chkBackup.Checked;
Properties.Settings.Default.Save();
}
There doesn't seem to be an Event for "CheckedChanged" in WPF, So I'm trying:
private void chkBackup_Checked(object sender, RoutedEventArgs e)
{
Properties.Settings.Default.Backup = (chkBackup.IsChecked == true);
Properties.Settings.Default.Save();
}
private void chkBackup_Unchecked(object sender, RoutedEventArgs e)
{
Properties.Settings.Default.Backup = (chkBackup.IsChecked == false);
Pr开发者_C百科operties.Settings.Default.Save();
}
I get no errors with this, but when I uncheck the checkBox, the settings aren't changed. Please help. What am I doing wrong.
Thanks
You're using a different expression each time. In the checked event you're using chkBackup.IsChecked == true
which evaluates to true if the box is checked and false otherwise.
In the unchecked event you're using chkBackup.IsChecked == false
which evaluates to true if the box isn't checked and false otherwise.
What you're interested in is if the box is checked or not. The expression to use for this is chkBackup.IsChecked == true
. Your current solution will always save true
.
you are using the Settings object correctly (from the code you provided), so maybe you need to attach the Checked/Unchecked event handlers.... (MSDN here)
<!-- in your xaml -->
<CheckBox Checked="OnChecked" Unchecked="OnUnchecked"/>
//in your code-behind....
myCheckbox.OnChecked += myHandler;
Your code looks fine. Are you hooking up your handlers in XAML?
<CheckBox Name="chkbox"
Content="Some Checkbox"
Checked="chkBackup_Checked"
Unchecked="chkBackup_Unchecked" />
If you want it to be a little more streamlined, you could do something like this:
<CheckBox Name="chkbox"
Content="Some Checkbox"
Checked="chkBackup_CheckChanged"
Unchecked="chkBackup_CheckChanged" />
private void chkBackup_CheckChanged(object sender, RoutedEventArgs e)
{
Properties.Settings.Default.Backup = chkBackup.IsChecked;
Properties.Settings.Default.Save();
}
I've found, that in WPF you can use strings to save a value. It's inconvenient, but it works. :/
private void chkBackup_Checked(object sender, RoutedEventArgs e)
{
Properties.Settings.Default.Backup = "true";
Properties.Settings.Default.Save();
}
private void chkBackup_Unchecked(object sender, RoutedEventArgs e)
{
Properties.Settings.Default.Backup = "false";
Properties.Settings.Default.Save();
}
and to check if it's checked, you can use
if (Properties.Settings.Default.Backup == "false")
{
//enter code here
}
精彩评论