WPF 将复选框绑定到布尔值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28383536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 12:55:17  来源:igfitidea点击:

WPF Bind checkbox to bool?

c#wpfxamlmvvmcheckbox

提问by Jim

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?

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

XAML:

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");
    }
}

采纳答案by eran otzap

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"); 
    }
}