Search code examples
c#wpfxamldata-bindingischecked

WPF CheckBox IsChecked Binding Issue


I have a binding that isn't working and rather than fixing it the only way I know how I would like to better understand why its not working and what options I have other than the one solution I know.

XAML:

<CheckBox Grid.Row="6" Grid.Column="1" IsChecked="{Binding Path=CurSerialPort.ExpansionEnabled}" Margin="7"  VerticalAlignment="Stretch" ToolTip="Select whether DHCP is enabled.">
   <CheckBox.Style>
      <Style TargetType="{x:Type CheckBox}" BasedOn="{StaticResource {x:Type CheckBox}}">
         <Style.Triggers>
            <DataTrigger Binding="{Binding Path=CurSerialPort.ShowExpansionEnable}" Value="False">
                <Setter Property="Visibility" Value="Collapsed" />
            </DataTrigger>
         </Style.Triggers>
      </Style>
   </CheckBox.Style>

Binding of issue:

IsChecked="{Binding Path=CurSerialPort.ExpansionEnabled}"

DataContext:

private void Page_Loaded(object sender, RoutedEventArgs e)
{
     this.DataContext = main.Model;
}

main.Model includes:

/// <summary>
/// The currently selected serial port
/// </summary>
public SerialModel CurSerialPort
{
   get { return this.curSerialPort; }
   set
   {
      if (value != null)
      {
         this.curSerialPort = value;
      }

      RaisePropertyChanged("CurSerialPort");
   }
}

SerialModel includes:

/// <summary>
/// Expansion Enable
/// </summary>
public bool ExpansionEnable
{
   get 
   { 
      return this.expansionEnable; 
   }
   set 
   {
      this.expansionEnable = value; 
   }
}

Being bound as it is isn't working. The set and get of the ExpansionEnable isn't reflecting the check box on the page.

I know I could just add:

public bool CurSerialPortExpansionEnable
{
   get { return CurSerialPort.ExpansionEnable; }
   set { CurSerialPort.ExpansionEnable = value; }
}

To the Model and the binding will work because this is how it has been done with properties related to the main model as a whole, although I dont want to have to keep adding single properties like this for every object that we have multiple instances of and would really like to find a solution where the binding is as above.

IsChecked="{Binding Path=CurSerialPort.ExpansionEnabled}"

Edit: Not sure what I changed but this does in fact completely work. Answer below pointed out a flaw of me forgetting the RaisePropertyChanged but other than that all seems good now.


Solution

  • Define isn't working. Are the get set even called?

    Try adding NotifyPropertyChanged to SerialModel

    public bool ExpansionEnable
    {
       get 
       { 
          return this.expansionEnable; 
       }
       set 
       {
          if(this.expansionEnable == value) return;
          this.expansionEnable = value; 
          RaisePropertyChanged("ExpansionEnable");
       }
    }
    

    If above does not work then take out the style and see if that is breaking something.
    But it looks good to me.