WPF 繫結基礎

weixin_33766168發表於2017-10-05

Binding是Wpf的核心內容之一

1、下面是Binding基礎的一個例子。

XAML:

<Grid>
    <TextBox x:Name="myTextBox" Height="80" HorizontalAlignment="Left" VerticalAlignment="Top" Width="200"/>
    <Button Height="23" HorizontalAlignment="Left" Margin="38,89,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click">Button</Button>
</Grid>

     C# Code

public partial class BindingTestxaml : Window
  {
      Customer cust;
      public BindingTestxaml()
      {
          InitializeComponent();
          BindingTest();
      }
      private void BindingTest()
      {
          //準備資料來源
          cust =  new Customer();
         // cust.Name = "Tom";
 
         //準備Binding
          Binding bind = new Binding();
          bind.Source = cust;
          bind.Path = new System.Windows.PropertyPath("Name");
 
          //使用Binding連線資料來源與Binding目標
          BindingOperations.SetBinding(myTextBox, TextBox.TextProperty, bind);
      }
 
      private void button1_Click(object sender, RoutedEventArgs e)
      {
          cust.Name += " Tom";
      }
  }
 
  public class Customer:INotifyPropertyChanged
  {
      private string name;
 
      public string Name
      {
          get { return name; }
 
          set
          {
              this.name = value;
              //激發事件
              if (PropertyChanged != null)
                  this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Name"));
 
          }
      }
 
      #region INotifyPropertyChanged 成員
 
      public event PropertyChangedEventHandler PropertyChanged;
 
      #endregion
  }

 當然上面的繫結也可以變成一句話的形式:如

//使用Binding連線資料來源與Binding目標
 BindingOperations.SetBinding(myTextBox, TextBox.TextProperty, new Binding("Name") { Source= cust =new Customer()});

 

2、沒有Source的Binding——使用DataContext作為Binding的源,下面是一個簡單的例子

先建立一個名為Sutdent的類,它有三個ID,Name,Age三個屬性:

public class Student
  {
      public string ID{ get; set;}
      public string Name { get; set; }
      public string Age { get; set; }
  }

然後XAML建立程式UI:

<StackPanel Background="LightBlue" Margin="0,118,0,0" HorizontalAlignment="Right" Width="201" Height="122" VerticalAlignment="Top">
    <StackPanel.DataContext>
        <local:Student  ID="10" Name="Work Hard Work Smart" Age="30"/>
    </StackPanel.DataContext>
    <TextBox Height="23" HorizontalAlignment="Center" Margin="10"  Name="textBox10" VerticalAlignment="Top" Text="{Binding Path=ID}"  Width="164" />
    <TextBox Height="23" HorizontalAlignment="Center" Margin="10" Name="textBox11" VerticalAlignment="Top" Text="{Binding Path=Name}"  Width="164" />
    <TextBox Height="23" HorizontalAlignment="Center"  Name="textBox12" VerticalAlignment="Top" Text="{Binding Path=Age}"  Width="164" />
</StackPanel>

三個TextBox的Text通過Binding獲取值,Bindng指定了Path,沒有指定Source。

 

 


本文轉自Work Hard Work Smart部落格園部落格,原文連結:http://www.cnblogs.com/linlf03/archive/2011/09/13/2175278.html,如需轉載請自行聯絡原作者

相關文章