Silverlight 复选框双向绑定未按预期工作
我在 Silverlight 3.0 中设置复选框的双向数据绑定时遇到简单的问题。这一定是理所当然的,但可能我今天忘记了我的大脑......
我定义了一个模型类来代表我的..“数据”。我实现了 INotifyPropertyChanged 接口,使 UI 能够看到数据何时发生变化。
public class Model : INotifyPropertyChanged
{
private bool _value;
public bool Value
{
get { return this._value; }
set
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs("Value"));
this._value = value;
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
接下来,我在 ..“表单”上放置了一个复选框和一个按钮:
<StackPanel Orientation="Horizontal">
<CheckBox x:Name="check" IsChecked="{Binding Value, Mode=TwoWay}" Content="SomeLabel"/>
<Button Click="Button_Click" Content="Test" />
</StackPanel>
然后我在构造函数中提供了数据:
public MainPage()
{
InitializeComponent();
this.DataContext = new Model() { Value = true };
}
问题是您必须在复选框上单击两次才能选中/取消选中,除非我取消实现 INotifyPropertyChanged 。但是,如果取消实现它,则 UI 不会注意到我是否更改了基础数据。
如果我从 IsChecked 绑定表达式中删除 Mode=TwoWay 位,那么即使模型正在实现接口,UI 也不会注意到底层数据的更改。
我该怎么做:
- 使复选框在启动时绑定到数据
- 使复选框 IsChecked 更改以修改基础数据
- 复选框是否检测基础数据更改并自行更新?
I have simple issue setting a two-way databinding of a checkbox in Silverlight 3.0. It must be a no-brainer but probably I forgot my brain home today...
I defined a Model class to represent my .. 'data'. I implemented the INotifyPropertyChanged interface to enable the UI to see when the data changes.
public class Model : INotifyPropertyChanged
{
private bool _value;
public bool Value
{
get { return this._value; }
set
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs("Value"));
this._value = value;
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
Next I put a checkbox and a button on the .. 'form' :
<StackPanel Orientation="Horizontal">
<CheckBox x:Name="check" IsChecked="{Binding Value, Mode=TwoWay}" Content="SomeLabel"/>
<Button Click="Button_Click" Content="Test" />
</StackPanel>
Then I supplied the data in the constructor :
public MainPage()
{
InitializeComponent();
this.DataContext = new Model() { Value = true };
}
The issue is that you have to click twice on the checkbox for it to check/uncheck unless I de-implement the INotifyPropertyChanged. If de-implement it however, then the UI doesn't notice if I change the underlying data.
If I remove the Mode=TwoWay bit from the IsChecked binding expression then also the UI won't notice the underlying data change even if the Model is implementing the interface.
How can I do to :
- Have the checkbox bound to the data at startup
- Have the checkbox IsChecked change to modify the underlying data
- Have the checkbox detect the underlying data change and update itself?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的设置属性过程中出现排序错误,您需要在通知更改之前分配
_value
:-You've got a sequencing error in your set property procedure, you need to assign to
_value
before notifying the change :-