WPF Bind checkbox to bool?
21,779
The reason for that is because it's initially null.
private bool? _mutualChb;
public bool? MutualChb
{
get { return (_mutualChb != null ) ? _mutualChb : false; }
set
{
_mutualChb = value;
OnPropertyChanged("MutualChb");
}
}
Author by
Jim
Updated on March 07, 2020Comments
-
Jim about 4 years
I have a WPF checkbox binded to ViewModel nullable boolean property. I am setting this property to false or true in Constructor, to avoid Interminent state but no matter what I do the Initial state of checkbox stays grayed. The binding working just fine since once I change the state by clicking the checkbox on UI I am getting controls values (true/false). Any Ideas?
XAML:
<CheckBox Margin="0,4,0,3" VerticalAlignment="Center" Content="Mutual" IsChecked="{Binding MutualChb}" />
ViewModel:
public ContstrutorViewModel() { MutualChb = true; } private bool? _mutualChb; public bool? MutualChb { get { return _mutualChb; } set { _mutualChb = value; _mutualChb = ( _mutualChb != null ) ? value : false; OnPropertyChanged("MutualChb"); } }
-
Federico Berasategui over 9 years
return (_mutualChb ?? false);
looks better -
eran otzap over 9 yearsYes @Jim i just went with your initial code but i would write (_mutualChb ?? false);