首页 > 代码库 > WPF双向绑定
WPF双向绑定
需求:
思想批量保存数据.
思路:
看了一下MVVM.发现只需要实现前台和后台数据的同步即可.也就是前台的文本框内容变化时后台的对象的属性也要变化就可以了.
参考:
http://www.cnblogs.com/luluping/archive/2011/05/06/2039475.html
该网址只包括单个对象,而我的需要把集合Bind到Datagrid上,在DataGrid上修改后在整批提交.思路是一样的.
即:类需从INotifyPropertyChanged继承
再定义好ViewModel,窗体和ViewModel 绑上就可以了.
public class Person : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private string name; public string Name { get { return name; } set { name = value; if(this.PropertyChanged != null) { this.PropertyChanged.Invoke(this,new PropertyChangedEventArgs("Name")); } } } }
ViewModel
public class PersonViewModel { public List<Person> LiPerson { get; set; } }
Form
public partial class MainWindow : Window { PersonViewModel personViewModel; public MainWindow() { InitializeComponent(); personViewModel = new PersonViewModel(); personViewModel.LiPerson = new List<Person>(); Person person = new Person(); person.Name = "xxx"; personViewModel.LiPerson.Add(person); Person person2 = new Person(); person2.Name = "asd"; personViewModel.LiPerson.Add(person2); this.DataContext = personViewModel; } private void Button_Click_1(object sender, RoutedEventArgs e) { MessageBox.Show(personViewModel.LiPerson[0].Name); MessageBox.Show(personViewModel.LiPerson[1].Name); } }
xaml
<Window x:Class="WpfStudy.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:my="http://schemas.microsoft.com/wpf/2008/toolkit" Title="MainWindow" Height="350" Width="525"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="30"></RowDefinition> <RowDefinition Height="400*"></RowDefinition> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="200"></ColumnDefinition> <ColumnDefinition Width="200*"></ColumnDefinition> </Grid.ColumnDefinitions> <Button Content="Button" Grid.Row="0" Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Click="Button_Click_1"/> <TextBox HorizontalAlignment="Left" Grid.Column="0" Height="23" TextWrapping="Wrap" Text="{Binding Path=Name}" VerticalAlignment="Top" Width="120"/> <my:DataGrid Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="5" AutoGenerateColumns="False" HorizontalAlignment="Left" Name="dgSupGridView" ItemsSource="{Binding Path=LiPerson,Mode=TwoWay}" ScrollViewer.HorizontalScrollBarVisibility="Auto" ScrollViewer.VerticalScrollBarVisibility="Auto" > <my:DataGrid.Columns> <my:DataGridTextColumn Header="Name" IsReadOnly="False" Width="100" Binding="{Binding Name}" /> </my:DataGrid.Columns> </my:DataGrid> </Grid></Window>
对mvvm不熟悉的同学就可以用这种方式来实现批量保存了.
WPF双向绑定
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。