WPF 复选框 IsChecked 绑定,OnpropertyChanged 不起作用

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

WPF checkbox IsChecked binding, OnpropertyChanged not working

wpfvb.netcheckboxdata-binding

提问by JMan

I have a checkboxin my view and the binding on it is working fine if i do any modification to my object and trigger the propertyChangedevent.

我有一个checkbox在我看来,如果我对我的对象进行任何修改并触发propertyChanged事件,它的绑定工作正常。

On the other side when i click my checkboxi perform some logic if the property where it is bound to can be changed. If not i change it back to False and trigger the propertyChangedevent.

另一方面,当我单击我的checkbox我执行一些逻辑,如果它绑定到的属性可以更改。如果不是,我将其改回 False 并触发propertyChanged事件。

My view is not updating this state of the checbox and it is still checked.

我的观点没有更新复选框的这个状态,它仍然被选中。

Is this a know problem with any bypass?

这是任何旁路的已知问题吗?

Code:

代码:

<ctrls:CheckBox 
   IsChecked="{Binding IsConverted, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

When i change the value and raise the property change event the property is retrieved with the false value:

当我更改值并引发属性更改事件时,将使用 false 值检索该属性:

Private _isConverted As Boolean
Public Property IsConverted As Boolean
    Get
        Return _isConverted
    End Get
    Set(value As Boolean)
        _isConverted = value
    End Set
End Property

回答by nvoigt

In your Binding in Xaml, make sure that Modeis set to TwoWayso the updates work in both directions.

在您的 Binding in 中Xaml,确保将Mode其设置为TwoWay使更新在两个方向都有效。

<CheckBox IsChecked="{Binding Path=ViewModelIsChecked, Mode=TwoWay}"/>

Also, now that you posted code, you seem to do things "manually", that should be implemented using the interface INotifyPropertyChanged. Can you drop the UpdateSourceTrigger and just implement INotifyPropertyChanged in your ViewModel?

此外,既然您发布了代码,您似乎是“手动”做事,应该使用接口 INotifyPropertyChanged 来实现。您可以删除 UpdateSourceTrigger 并在您的 ViewModel 中实现 INotifyPropertyChanged 吗?

There is a good guide here.

有一个很好的指导这里

Edit: And because the Poster isn't willing or able to read and understand the guide, here comes the code that is posted there:

编辑:并且由于海报不愿意或无法阅读和理解指南,因此发布在那里的代码如下:

Public Property PhoneNumber() As String 
    Get 
        Return Me.phoneNumberValue
    End Get 

    Set(ByVal value As String)
        If Not (value = phoneNumberValue) Then 
            Me.phoneNumberValue = value
            NotifyPropertyChanged()          <===== THIS LINE IS DIFFERENT! YOU DON'T HAVE IT. YOU NEED IT.
        End If 
    End Set 
End Property