• Simple Data Binding in Silverlight 4.0


    To help explain data binding in Silverlight, let's build a very simple application. The application will include a Book object that contains two properties: Title and ISBN. These properties will be bound to two Text Controls. Results as following:

    1. Create a new Silverlight application in Visual Studio 2010. Name the project BasicDataBinding, and allow Visual Studio to create a Web application project to host your application.

    2. Edit the MainPage.xaml file to define two columns and six grid rows. Place a TextBlock in each row in column1 and a TextBOx in each row in column2. Also add some margins and some alignment assignments to improve the layout. The code for the page follows:

    <Grid x:Name="LayoutRoot" Background="White">

      <Grid.RowDefinitions>

        <RowDefinition />

        <RowDefinition />

        <RowDefinition />

        <RowDefinition />

        <RowDefinition />

        <RowDefinition />

      </Grid.Rowdefinitions>this.

      <Grid.ColumnDefinitions>

        <ColumnDefinition width="Auto" />

        <ColumnDefinition />

      </Grid.ColumnDefinitions>

      <TextBlock Text="Book Title" VerticalAlignment = "center" Margin="5" />

      <TextBlock Text="ISBN-13" VerticalAlignment="Center" Margin="5" Grid.Row="1" />

      <TextBox Text="{Binding Title}" Height="24" Margin="5" Grid.Column="1" />

      <TextBox Text="{Binding ISBN}" Height="24" Margin="5" Grid.Column="1" Grid.Row="1" />

      <TextBlock Text="Book Title" VerticalAlignment = "center" Margin="5" Grid.Row="2"  />

      <TextBlock Text="ISBN-13" VerticalAlignment="Center" Margin="5" Grid.Row="3" />

      <TextBox Text="{Binding Title}" Height="24" Margin="5" Grid.Column="1" Grid.Row="2"  />

      <TextBox Text="{Binding ISBN}" Height="24" Margin="5" Grid.Column="1" Grid.Row="3" />

     </Grid>

    3. Next, edit the code behind, MainPage.Xaml.cs. Add a loaded event handler for the application, which will fire when application is loaded by the client. This is accomplished with the following source code:

    public partical class MainPage:UserControl

    {

      public MainPage()

      {

        InitializeComponent();

        this.Loaded+= new RoutedEventHandler(Page_Loaded);

      }

      void Page_Loaded(object sender, RoutedEventArgs e)

      {    

      }

    }

    Now you need to add a class to define a Book object. Below the MainPage Class, add the following class definition:

    public class Book

    {    

      public string Title {get;set;}

      public string ISBN {get;set;}

    }

     4. Now that you have Book defined, you need to create an instance of Book and Set it to the LayoutRoot's DataContext, as follows:

    void Page_Loaded(object sender, RoutedEventArgs e)

    {

      Book b= new Book()

      {

        Title="aaaaaaaaaaaaaaaaaaaaaaa", ISBN="33333333333333"  

      };

      this.LayoutRoot.DataContext=b;

    }

    when you set up binding definitions for different controls, the controls do not know where they are going to get their data. The datacontext property sets the data context for a control that is participating in data binding. The DataContext property can be set directly on the control. If a given control does not have a dataContext property specified, it will look to its parent for its data context. The nice thing about this model is that if you look above in the XAML for the page, you will see little indication of where the conrols are getting their data. This provides an extreme level of code sepatation, allowing designers to design XAML UIs and developers to work alongside the designers, defining thespecifics of how the controls are bound to their data sources.

    5. At this point, you can go ahead and start debugging the application. If all goes well, you will see the four text boxes populated with the data from the Book's instance.

    6. With the application running, change the book title in thr first text box to just "Beginning Silverlight", by removing the "From Novice to Professional".

     You might expect that, since the third text box is bound to the same data, it will automatically update to reflect this change. Howeve, a couple of things need to be done to get this type of two-way  binding to work.

    One problem is that, currently, the Book class does not support notifying bound clients of changes to its properties. In other words, when a property changes in Book, the class will not notify the TextBox instances that are bound to the chass of the change. You could take care of this by creating a change event for each property. This is far from ideal; fortunately, there is an interface that a class can implement that handles this for you. This interface is known as INotifyPropertyChanged. let's use it.

    7 Mofify the Book class definition to inherit from INotifyPropertyChanged. Notice that when you inherit from INotifypropertyChanged, you need to add using System.ComponentModel. Luckily, VS wil help you with this.

    Next, you can let VS do some more work for you. After adding the using System.ComponentModel statement, right-click INotifyPropertyChanged and select Implement Interface->Implement Interface from the pop-up menu.

    8. Next, you need to create a convenience method that will fire the PropertyChanged event. Call it FirePropertyChanged, as shown in the following code:

      public class Book : INotifyPropertyChanged

      {

        public string Title { get; set; }
          public string ISBN { get; set; }

        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

            void FirePropertyChanged(string property)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this,new System.ComponentModel.PropertyChangedEventArgs(property));
                }
            }

      }

    9. Now you need to extend the simplified properties by adding private memebers and full get/set definitions to define the get and set operations, as shown in the following code. The get is just like a normal get operation, where you simply return the internal member value. For the set, you first set the interval member value, and then call the FirePropertyChanged method, passing it the name of the property.

    public class Book:System.ComponentModel.INotifyPropertyChanged
        {
            private string _title;
            private string _isbn;
            public string Title
            {
                get { return _title; }
                set
                {
                    _title = value;
                    FirePropertyChanged("Title");
                }
            }

            public string ISBN
            {
                get { return _isbn; }
                set
                {
                    _isbn = value;
                    FirePropertyChanged("ISBN");
                }
            }


            public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

            void FirePropertyChanged(string property)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this,new System.ComponentModel.PropertyChangedEventArgs(property));
                }
            }

    With this completed, your class is set up to notify bound  clients of changes to the Title and ISBN properties. But you still need to take one more stip. By default, when you bind a source to a target, the BindingMode is set to OneWay binding,whick means that the source will send the data to the target, but the target will not send data changes back to the source. In order to get the target to update the source, you need to implement tw-way(TwoWay)binding.

    10. To change to two-way binding, add the Mode=TwoWay parameter when defining the {Binding} on a control, as follows:

    <TextBlock Text="Book Title" VerticalAlignment = "center" Margin="5" />
            <TextBlock Text="ISBN-13" VerticalAlignment="Center" Margin="5" Grid.Row="1" />
            <TextBox Text="{Binding Title, Mode=TwoWay}" Height="24" Margin="5" Grid.Column="1" />
            <TextBox Text="{Binding ISBN, Mode=TwoWay}" Height="24" Margin="5" Grid.Column="1" Grid.Row="1" />
            <TextBlock Text="Book Title" VerticalAlignment = "center" Margin="5" Grid.Row="2"  />
            <TextBlock Text="ISBN-13" VerticalAlignment="Center" Margin="5" Grid.Row="3" />
            <TextBox Text="{Binding Title, Mode=TwoWay}" Height="24" Margin="5" Grid.Column="1" Grid.Row="2"  />
            <TextBox Text="{Binding ISBN, Mode=TwoWay}" Height="24" Margin="5" Grid.Column="1" Grid.Row="3" />

    11. Rebuild and run your application. Update any of the fields, and leave the focus one the control. You'll see that the two-way binding is triggered, and the corresponding field is also updated.

  • 相关阅读:
    C#验证类(使用正则表达式)
    SQL数据库还原语句
    JS键盘或鼠标事件
    列表针对列宽度自动调整显示内容,超长以...缩写结尾
    SQL按照日、周、月、年统计数据 (转自BLEACH的blog)
    SQL利用Case When Then多条件判断
    调用Web服务:请求因HTTP状态401失败:Unauthorized
    IFrame自动适应宽高,去掉空白
    Asp调用WebService事例
    Timer不执行Elapsed事件的解决办法
  • 原文地址:https://www.cnblogs.com/jerrychenfly/p/2139155.html
Copyright © 2020-2023  润新知