简体   繁体   English

WPF CheckBox.IsChecked绑定

[英]WPF CheckBox.IsChecked binding

I have a datagrid with a variable number of columns that I am generating programatically. 我有一个数据网格,该网格以编程方式生成了可变数量的列。 It contains DataGridTemplateColumns, each with a DockPanel containing a CheckBox and a TextBlock. 它包含DataGridTemplateColumns,每个都有一个包含CheckBox和TextBlock的DockPanel。

Binding code: 绑定代码:

    Binding bindingPicked = new Binding(string.Format("Prices[{0}].Picked", i));
    bindingPicked.Mode = BindingMode.TwoWay;

CheckBox code: 复选框代码:

    FrameworkElementFactory factoryCheckBox = new FrameworkElementFactory(typeof(CheckBox));
    factoryCheckBox.SetValue(CheckBox.IsCheckedProperty, bindingPicked);

Picked property: 选择的属性:

    private bool _picked;
    public bool Picked
    {
        get { return _picked; }
        set { _picked = value; }
    }

When the datagrid is initialized, the Picked getters are called as expected. 初始化数据网格后,将按预期方式调用Picked getter。 However, when I check/uncheck a checkbox, the setter isn't called. 但是,当我选中/取消选中复选框时,不会调用设置器。 What is causing this? 是什么原因造成的? I do not want to use a DependencyProperty, and I don't think it should be needed as I just need the property setter to be called when the user clicks the CheckBox. 我不想使用DependencyProperty,并且我认为不需要,因为我只需要在用户单击CheckBox时调用属性设置器即可。

EDIT: Apparently I am a moron, I simply forgot bindingPicked.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; 编辑:显然我是个白痴,我只是忘记了bindingPicked.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; Feel free to close this. 随时关闭它。

bindingPicked.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;

那应该做的:)

我认为您应该实现INotifyPropertyChanged并在set中调用该事件

As above, you need to implement INotifyPropertyChanged The correct pattern to follow is: 如上所述,您需要实现INotifyPropertyChanged。遵循的正确模式是:

private bool _picked;
public bool Picked
{
    get { return _picked; }
    set
    {
        if (_picked != value)
        {
            _picked = value;
            if (null != PropertyChanged)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("Picked"));
            }
        }
    }
}

The UpdateSourceTrigger property tells databinding when to update the source. UpdateSourceTrigger属性告诉数据绑定何时更新源。 For example, with a TextBox, the default is LostFocus. 例如,对于TextBox,默认值为LostFocus。 For most other controls it is PropertyChanged. 对于大多数其他控件,它是PropertyChanged。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM