WPF绑定复选框bool?

时间:2015-02-07 14:49:50

标签: c# wpf xaml mvvm checkbox

我有一个绑定到ViewModel可以为空的布尔属性的WPF复选框。我在构造函数中将此属性设置为false或true,以避免Interminent状态,但无论我做什么,复选框的初始状态保持灰色。绑定工作正常,因为一旦我通过单击UI上的复选框更改状态,我将获得控件值(true / false)。任何想法?

XAML:

<CheckBox Margin="0,4,0,3"
          VerticalAlignment="Center"
          Content="Mutual"
          IsChecked="{Binding MutualChb}" />

视图模型:

public ContstrutorViewModel()
{
    MutualChb = true;
}

private bool? _mutualChb;
public bool? MutualChb
{
    get { return _mutualChb; }
    set
    { 
        _mutualChb = value; 
        _mutualChb = ( _mutualChb != null ) ? value : false;
        OnPropertyChanged("MutualChb");
    }
}

1 个答案:

答案 0 :(得分:2)

原因是因为它最初为空。

private bool? _mutualChb;
public bool? MutualChb
{
    get { return (_mutualChb != null ) ? _mutualChb : false; }
    set
    { 
        _mutualChb = value;               
        OnPropertyChanged("MutualChb"); 
    }
}