首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 媒体动画 > CAD教程 >

[Silverlight入门系列]应用MVVM模式(3):Model的INotifyPropertyChanged接口实现

2012-11-07 
[Silverlight入门系列]使用MVVM模式(3):Model的INotifyPropertyChanged接口实现ObservableCollection自动

[Silverlight入门系列]使用MVVM模式(3):Model的INotifyPropertyChanged接口实现

ObservableCollection自动实现(见上一篇))

一个简单的例子:(下面的例子中TextBlock绑定了DataContext的ModelName,点击按钮以后model更新,TextBlock会自动更新)

Model:

 1 public class MyModel : INotifyPropertyChanged    2 { 3         public event PropertyChangedEventHandler PropertyChanged;    4  5         public int ModelID { get; set; } 6  7         private string _ModelName; 8         public string ModelName 9         {10             get { return _ModelName; }11             set12             {13                 _ModelName = value; 14 15                 if (PropertyChanged != null)16                 {17                     PropertyChanged(this, new PropertyChangedEventArgs("ModelName"));18                 }19             }20         }21 }

?

Silverlight页面:

1 <Grid x:Name="LayoutRoot" Background="White">2         <TextBlock Height="46" HorizontalAlignment="Left" Margin="187,51,0,0" Name="textBlock1" Text="{Binding ModelName}" VerticalAlignment="Top" Width="94" />3         <Button Content="update" Height="39" HorizontalAlignment="Left" Margin="187,120,0,0" Name="button1" VerticalAlignment="Top" Width="106" Click="button1_Click" />4  </Grid>

?

页面代码:

 1 public MyView() 2 { 3       InitializeComponent(); 4  5       MyModel m1 = new MyModel() { ModelID = 1, ModelName = "abc" }; 6  7       this.DataContext = m1; 8 } 9 10  private void button1_Click(object sender, RoutedEventArgs e)11 {12        (this.DataContext as MyModel).ModelName = "abc_changed";13 }

甚至还有一个VS2010插件来完成这个工作:NotifyPropertyWeaver

ViewModel也可以实现INotifyPropertyChanged接口,很简单:

XAML绑定集合:

1 <DataGrid ItemsSource="{Binding Path=LineItems}" />

?

ViewModel代码:

 1 public class OrderViewModel : INotifyPropertyChanged 2 { 3     public OrderViewModel( IOrderService orderService ) 4     { 5         this.LineItems = new ObservableCollection<OrderLineItem>( 6                                orderService.GetLineItemList() ); 7     } 8  9     public ObservableCollection<OrderLineItem> LineItems { get; private set; }10 }

热点排行