Silverlight 自修計畫 Binding
自訂類別
{
public String Name { get; set; }
public String Tel { get; set; }
public Int32 width { get; set; }
public System.Windows.Media.Brush bruch1 { get; set; } //筆刷
}
主程式
{
InitializeComponent();
MyClass ob1 = new MyClass() { Name = "王大明",
Tel="07-1234567",
width=80,
bruch1 = new SolidColorBrush(Colors.Red)}; //初始化物件
this.myName.DataContext = ob1; //Binding MyName TextBox 物件
this.myTel.DataContext = ob1; //Binding MyTel TextBox 物件
MyClass ob2 = new MyClass() { Name = "陳小華",
Tel = "08-7654321",
width = 90,
bruch1 = new SolidColorBrush(Colors.Green) }; //初始化物件
//後端程式碼宣告綁定:文字內容
System.Windows.Data.Binding MyBindingText = new Binding();
MyBindingText.Path = new PropertyPath("Name"); //綁定物件屬性名稱
MyBindingText.Mode = BindingMode.OneTime; //選擇 一次性
MyBindingText.Source = ob2; //指定 Source來源
this.myCode.SetBinding(TextBox.TextProperty, MyBindingText);//指定控制項物件要綁定的屬性與Binding物件
//後端程式碼宣告綁定 :字體顏色
System.Windows.Data.Binding MyBindingColor = new Binding();
MyBindingColor.Path = new PropertyPath("bruch1"); //綁定物件屬性名稱
MyBindingColor.Mode = BindingMode.OneTime; //選擇 一次性
MyBindingColor.Source = ob2; //指定 Source來源
this.myCode.SetBinding(TextBox.ForegroundProperty, MyBindingColor); //指定控制項物件要綁定的屬性與Binding物件
}
XML宣告
<StackPanel>
<TextBox x:Name="myName" Text="{Binding Name,Mode=OneTime}" Width="{Binding width,Mode=OneTime}"></TextBox> <!--綁定文字與寬度-->
<TextBox x:Name="myTel" Text="{Binding Tel,Mode=OneTime}" Foreground="{Binding bruch1, Mode=OneTime}"></TextBox> <!--綁定文字與顏色-->
<TextBox x:Name="myCode" Text="Text" ></TextBox> <!--使用程式碼綁定-->
</StackPanel>
</Grid>
結果