(一)前台代码:
- <Grid x:Name="LayoutRoot" Background="White">
- <StackPanel>
- <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
- <TextBlock Height="23" Name="textBlock1" Text="编号" Width="34" />
- <TextBox Text="{Binding ID,Mode=OneTime}" Name="tbxID" Width="106" Height="27" ></TextBox>
- </StackPanel>
- <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
- <TextBlock Height="23" Name="textBlock2" Text="书名:" />
- <TextBox Text="{Binding Title,Mode=OneWay}" Name="tbxTitle" Width="108" Height="27" ></TextBox>
- </StackPanel>
- <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
- <TextBlock Height="23" Name="textBlock3" Text="价格:" VerticalAlignment="Top" />
- <TextBox Text="{Binding Price,Mode=TwoWay}" Name="tbxPrice" Width="108" Height="27"></TextBox>
- </StackPanel>
- <StackPanel>
- <Button Name="MyButton" Content="通过数据源修改控件的值" Click="MyButton_Click" Width="140" Height="27"></Button>
- <Button Content="直接修改控件的值" Height="23" Name="button1" Width="139" Click="button1_Click" />
- <Button Content="通过控件修改数据源的值" Height="23" Name="button2" Width="140" Click="button2_Click" />
- </StackPanel>
- </StackPanel>
-
- </Grid>
(二)后台代码
- public partial class MainPage : UserControl
- {
- Book book = new Book();
- public MainPage()
- {
- InitializeComponent();
- book.ID = 0;
- book.Title = "ASP.NET 开发手册";
- book.Price = 40;
- tbxID.DataContext = book;
- tbxTitle.DataContext = book;
- tbxPrice.DataContext = book;
- }
-
-
-
-
-
- private void MyButton_Click(object sender, RoutedEventArgs e)
- {
- book.ID = 100;
- book.Price = 50;
- book.Title = "SL开发手册";
- }
-
-
-
-
-
-
- private void button2_Click(object sender, RoutedEventArgs e)
- {
- MessageBox.Show(book.ID.ToString() + " " + book.Title.ToString() + " " + book.Price.ToString());
- }
-
-
-
- private void button1_Click(object sender, RoutedEventArgs e)
- {
- tbxID.Text = "100";
- tbxPrice.Text = "50";
- tbxTitle.Text = "SL开发手册";
- }
-
- }
- public class Book:INotifyPropertyChanged
- {
- private int _id;
- public int ID
- {
- get { return _id; }
- set
- {
- _id = value;
- NotifyPropertyChange("ID");
- }
- }
- private string _title;
- public string Title
- {
- get { return _title; }
- set
- {
- _title = value;
- NotifyPropertyChange("Title");
- }
- }
- private double _price;
- public double Price
- {
- get { return _price; }
- set
- {
- _price = value;
- NotifyPropertyChange("Price");
- }
- }
- public event PropertyChangedEventHandler PropertyChanged;
- private void NotifyPropertyChange(string propertyName)
- {
- if (PropertyChanged != null)
- {
- PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
- }
- }
- }
(三)总结:
数据源--》控件 的更改就只能用OneWay,TwoWay并且需要实现INotifyPropertyChanged接口,而控件---》数据源,只有使用TwoWay方式才可以修改数据源(且不需要实现INotifyPropertyChanged接口)。然而直接更改控件值,虽然这样能更改控件Text属性值,但要进行类型转换,在这里都要转换为字符串类型。所以我们在操作是常用实体来接收参数,而不是直接去控件的值!
全文转自:http://blog.csdn.net/Joetao/archive/2010/08/11/5803716.aspx
|