View的C#代码


using System.Windows; namespace WpfApplication4 { /// <summary> /// Interaction logic for RegisterUserView.xaml /// </summary> public partial class RegisterUserView : Window { public RegisterUserView() { InitializeComponent(); this.ViewModel = new RegisterUserViewModel(); this.ViewModel.View = this; this.ViewModel.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(ViewModel_PropertyChanged); } void ViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { // this.tbAge.Text = this.ViewModel.Age.ToString(); ; } public RegisterUserViewModel ViewModel { get { return this.DataContext as RegisterUserViewModel; } set { this.DataContext = value; } } } }
View的XAML代码
<Grid> <Button Height="23" HorizontalAlignment="Left" Margin="12,0,0,72" Name="btnClick" VerticalAlignment="Bottom" Width="75" Command="{Binding ClickCommand}">Click me</Button> <TextBlock Height="21" Margin="12,44,0,0" Name="textBlock1" VerticalAlignment="Top" Text="UserName:" HorizontalAlignment="Left" Width="62" /> <TextBlock Margin="12,93,0,0" Name="textBlock2" Height="21" HorizontalAlignment="Left" VerticalAlignment="Top" Width="62" Text="Age:" /> <TextBlock Height="21" Margin="99,44,117,0" Name="tbUserName" Text="{Binding Path=UserName, Mode=OneTime}" VerticalAlignment="Top" /> <TextBlock Height="21" Margin="99,93,117,0" Name="tbAge" Text="{Binding Age}" VerticalAlignment="Top" /> </Grid>
这两行是在View里面把ViewModel绑定到Windows.DataContext,这样在XAML里才可以藉由后期用Text="{Binding Age}"绑定,
命今是通过Command="{Binding ClickCommand}"绑定,Age和ClickCommand是在RegisterUserViewModel中实现的
this.ViewModel = new RegisterUserViewModel();
this.ViewModel.View = this;
下面把RegisterUserViewModel的代码贴出来,RegisterUserViewModel实现了INotifyPropertyChanged,所以可以在View中编写响应这个事件的委托,以便及时刷新View,但在此例中不在View中编写委托也可以,因为ViewModule已经绑定到tbAge的Text属性上了,注意到Age是int类型,Text是string类型,自动做了类型转换的工作.
<TextBlock Height="21" Margin="99,93,117,0" Name="tbAge" Text="{Binding Age}" VerticalAlignment="Top" />
namespace WpfApplication4 { public class RegisterUserViewModel : INotifyPropertyChanged { public RegisterUserViewModel() { this.UserName = "Baobao"; this.Age = 27; ClickCommand = new DelegateCommand<object>(OnClick, arg => true); } void OnClick(object obj) { this.Age += 1; } public RegisterUserView View { get; set; } public ICommand ClickCommand { get; set; } public string UserName { get; set; } private int age; public int Age { get { return this.age; } set { if (this.age != value) { this.age = value; //如果直接引用View则耦合了 //if(View!=null) View.tbAge.Text = value.ToString() ; OnPropertyChanged("Age"); } } } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = this.PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } #endregion } }