WPF CheckBox双向绑定不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16094679/
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 08:37:42  来源:igfitidea点击:

WPF CheckBox TwoWay Binding not working

wpfxamlcheckboxbinding

提问by Matt

I have

我有

 <DataGridCheckBoxColumn 
     Binding="{Binding Path=Foo, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
 />

And

 public bool Foo{ get; set; }

Checking/Unchecking sets Foo, but setting Fooin code does not change the Checkbox state. Any Suggesitons?

Checking/Unchecking set Foo,但Foo在代码中设置不会改变 Checkbox 状态。任何建议?

回答by Andrew

You need to raise the PropertyChangedevent when you set Foo in your DataContext. Normally, it would look something like:

您需要提高PropertyChanged当您在设置富事件DataContext。通常,它看起来像:

public class ViewModel : INotifyPropertyChanged
{
    private bool _foo;

    public bool Foo
    {
        get { return _foo; }
        set
        {
            _foo = value;
            OnPropertyChanged("Foo");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        var propertyChanged = PropertyChanged;
        if (propertyChanged != null)
        {
            propertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

If you call Foo = someNewvalue, the PropertyChangedevent will be raised and your UI should be updated

如果您调用Foo = someNewvaluePropertyChanged将引发该事件并且您的 UI 应该更新

回答by pwrgreg007

I spent hours looking for a complete answer to this issue. I guess some people assume that other people searching this issue know the basics - sometimes we don't. A very important part about setting the form's data context was usually missing:

我花了几个小时寻找这个问题的完整答案。我猜有些人认为搜索此问题的其他人知道基础知识 - 有时我们不知道。通常缺少设置表单数据上下文的一个非常重要的部分:

    public YourFormConstructor()
    {
        InitializeComponent();
        DataContext = this;                 // <-- critical!!
    }

My checkbox control was set up in the xaml file like this:

我的复选框控件是在 xaml 文件中设置的,如下所示:

<CheckBox x:Name="chkSelectAll" IsChecked="{Binding chkSelectAllProp, Mode=TwoWay}" HorizontalAlignment="Left"/>

The "Path=" and "UpdateSourceTrigger=..." parts appear to be optional, so I left them out.

“Path=”和“UpdateSourceTrigger=...”部分似乎是可选的,所以我将它们排除在外。

I am using this checkbox in a ListView header column. When someone checks or unchecks the checkbox, I want all the items in the ListView to also be checked or unchecked (select/unselect all functionality). I left that code in the example (as "optional logic") but your checkbox value logic (if any) would replace this.

我在 ListView 标题列中使用此复选框。当有人选中或取消选中复选框时,我希望 ListView 中的所有项目也被选中或取消选中(选择/取消选择所有功能)。我在示例中留下了该代码(作为“可选逻辑”),但您的复选框值逻辑(如果有)将替换它。

The ListView contents are set by browsing for a file, and when a new file is selected, code sets the ListView ItemsSource and the CheckBox is checked (selecting all the new ListView items), which is why this two-way operation is required. That portion of the code is not present in this example.

The ListView contents are set by browsing for a file, and when a new file is selected, code sets the ListView ItemsSource and the CheckBox is checked (selecting all the new ListView items), which is why this two-way operation is required. 此示例中不存在该部分代码。

The code in the xaml.cs file to handle the CheckBox looks like this:

xaml.cs 文件中用于处理 CheckBox 的代码如下所示:

    // backing value
    private bool chkSelectAllVal;

    // property interchange
    public bool chkSelectAllProp
    {
        get { return chkSelectAllVal; }
        set
        {
            // if not changed, return
            if (value == chkSelectAllVal)
            {
                return;
            }
            // optional logic
            if (value)
            {
                listViewLocations.SelectAll();
            }
            else
            {
                listViewLocations.UnselectAll();
            }
            // end optional logic
            // set backing value
            chkSelectAllVal = value;
            // notify control of change
            OnPropertyChanged("chkSelectAllProp");
        }
    }

    // object to handle raising event
    public event PropertyChangedEventHandler PropertyChanged;

    // Create the OnPropertyChanged method to raise the event
    protected void OnPropertyChanged(string name)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }