WPB Databinding CheckBox.IsChecked

How to bind an IsChecked member from a CheckBox to a member variable in my form?

(I understand that I can access it directly, but I'm trying to find out about data binding and WPF)

Below is my unsuccessful attempt to get this to work.

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> 

the 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 always false } } } 
+7
checkbox data-binding wpf
source share
3 answers
 <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 if you want it to be updated as it changes.

+12
source share

Adding to @Will's answer: here is what your DependencyProperty (created using Dr. WPF fragments ) might look like:

 #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 
+2
source share

You should make your bind mode like TwoWay:

 <Checkbox IsChecked="{Binding Path=ShowPending, Mode=TwoWay}"/> 
0
source share

All Articles