WPF Databinding CheckBox.IsChecked
40,281
Solution 1
<Window ... Name="MyWindow">
<Grid>
<CheckBox ... IsChecked="{Binding ElementName=MyWindow, Path=ShowPending}"/>
</Grid>
</Window>
Note i added a name to <Window>
, and changed the binding in your CheckBox. You will need to implement ShowPending as a DependencyProperty
as well if you want it to be able to update when changed.
Solution 2
Addendum to @Will's answer: this is what your DependencyProperty
might look like (created using Dr. WPF's snippets):
#region ShowPending
/// <summary>
/// ShowPending Dependency Property
/// </summary>
public static readonly DependencyProperty ShowPendingProperty =
DependencyProperty.Register("ShowPending", typeof(bool), typeof(MainViewModel),
new FrameworkPropertyMetadata((bool)false));
/// <summary>
/// Gets or sets the ShowPending property. This dependency property
/// indicates ....
/// </summary>
public bool ShowPending
{
get { return (bool)GetValue(ShowPendingProperty); }
set { SetValue(ShowPendingProperty, value); }
}
#endregion
Author by
Adam Tegen
Updated on May 20, 2020Comments
-
Adam Tegen almost 4 years
How would I bind the IsChecked member of a CheckBox to a member variable in my form?
(I realize I can access it directly, but I am trying to learn about databinding and WPF)
Below is my failed attempt to get this working.
XAML:
<Window x:Class="MyProject.Form1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Title" Height="386" Width="563" WindowStyle="SingleBorderWindow"> <Grid> <CheckBox Name="checkBoxShowPending" TabIndex="2" Margin="0,12,30,0" Checked="checkBoxShowPending_CheckedChanged" Height="17" Width="92" VerticalAlignment="Top" HorizontalAlignment="Right" Content="Show Pending" IsChecked="{Binding ShowPending}"> </CheckBox> </Grid> </Window>
Code:
namespace MyProject { public partial class Form1 : Window { private ListViewColumnSorter lvwColumnSorter; public bool? ShowPending { get { return this.showPending; } set { this.showPending = value; } } private bool showPending = false; private void checkBoxShowPending_CheckedChanged(object sender, EventArgs e) { //checking showPending.Value here. It's always false } } }
-
Pat over 13 yearsIf the property is in a
ViewModel
rather than theView
itself, how would you do the binding? -
Will Eddins over 13 yearsIf using a ViewModel, you would typically set your DataContext within your View (or in the XAML) to your ViewModel, and simply do
IsChecked="{Binding ShowPending}"
-
Rob almost 6 yearsAlthough OneWay is the default for many properties, the IsChecked property is TwoWay by default. See Binding Overview