这是在WPF/C#中使用Binding的典型INotifyPropertyChanged实现.
namespace notifications.ViewModel
{
class MainViewModel : INotifyPropertyChanged
{
public const string NamePropertyName = "CheckBoxState";
private bool _checkboxstate = true;
public bool CheckBoxState
{
get { return _checkboxstate; }
set
{
if (_checkboxstate == value) return;
_checkboxstate = value;
RaisePropertyChanged(NamePropertyName);
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我还有一个绑定的XAML代码CheckBoxState
.
<Grid>
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<CheckBox Content="Click Me" IsChecked="{Binding Path=CheckBoxState, Mode=TwoWay}" />
<TextBlock Text="{Binding Path=CheckBoxState, Mode=TwoWay}" />
</StackPanel>
</Grid>
Run Code Online (Sandbox Code Playgroud)
这是MainWindow.xaml.cs,用于在DataContext和模型之间建立链接.
public partial class MainWindow : Window
{
notifications.ViewModel.MainViewModel model = new notifications.ViewModel.MainViewModel();
public MainWindow()
{
InitializeComponent();
this.DataContext = model;
}
}
Run Code Online (Sandbox Code Playgroud)
当用户设置的复选框,我想会发生什么情况如下:IsChecked
为真,并与"{Binding Path=CheckBoxState, Mode=TwoWay}"
,CheckBoxState
财产变成真正的呼吁RaisePropertyChanged()
,并相应地PropertyChanged()
.作为此函数的参数,通知CheckBoxState
每个带路径的Binding都会CheckBoxState
自行更新.
<TextBlock Text="{Binding Path=CheckBoxState, Mode=TwoWay}" />
?C#背后的魔力是什么让它成为可能?if (PropertyChanged != null)
必要?谁设置PropertyChanged到什么价值?Mode=TwoWay
看起来它的含义不仅可以指示更改,还可以在绑定中具有相同名称的其他Binding元素更改时更新内容,那么OneWay模式呢?我们可以将Binding仅设置为源或仅设置目标吗?Jac*_*ope 19
这个电话是如何激活的?C#背后的魔力是什么让它成为可能?
此代码创建一个Binding
对象,该对象将TextBlock的Text属性链接到ViewModel属性.它还为ViewModel的PropertyChanged事件添加了一个事件处理程序,以便在ViewModel触发PropertyChanged事件(具有正确的属性)时更新文本值.
为什么有
if (PropertyChanged != null)
必要?谁设置PropertyChanged到什么价值?
如果PropertyChanged事件为null,则触发它将导致NullReferenceException.
Mode=TwoWay
看起来它的含义不仅可以指示更改,还可以在绑定中具有相同名称的其他Binding元素更改时更新内容,那么OneWay模式呢?我们可以将Binding仅设置为源或仅设置目标吗?
绑定模式是:
你可以在这里阅读更多关于它们的信息:http://msdn.microsoft.com/en-us/library/system.windows.data.bindingmode.aspx
归档时间: |
|
查看次数: |
14115 次 |
最近记录: |