1. 程式人生 > WINDOWS開發 >wpf---資料繫結:

wpf---資料繫結:

1,資料繫結的幾種方式:

技術分享圖片

技術分享圖片

重點解釋以下幾點:1,目標物件的屬性是依賴項屬性.

2,對於Default方式,當目標屬性可以設定時,則是雙向繫結,否則是單向繫結.

2,使用程式碼繫結和解除繫結:

            Binding binding = new Binding();
            binding.Source = silderFontSize;//繫結資料來源
            binding.Path = new PropertyPath("Value");//注意 使用新類 PropertyPath
            binding.Mode = BindingMode.TwoWay;
            txtBlock.SetBinding(TextBox.TextProperty,binding);//注意 不是 txtBlock.Text---這是string型別,而是TextBlock.TextProperty

獲取繫結:

Binding binding = BindingOperations.GetBinding(obj,dependencyProperty)//獲取繫結
BindingExpression expression = BindingOperations.GetBindingExpression(obj,dependencyProperty);
object SourceObj = expression.ResolvedSource;
//操作源物件.

3,對於TextBox,雖然是雙向繫結,但是隻有在失去焦點時候才更新值,所以,可以設定 更新源的方式:

反向更新並不會立刻發生: 這取決於目標屬性的方式:

技術分享圖片

Delay: 設定延遲觸發源的時間.


利用expression.UpdateSource進行源更新.

  Binding binding = new Binding();
            binding.Source = this;
            binding.Path = ContentBox");
            binding.Mode = BindingMode.TwoWay;
            binding.UpdateSourceTrigger = UpdateSourceTrigger.Explicit;
            inputBox.SetBinding(TextBox.TextProperty,binding);

利用XAML的RelativeSource方法進行測試

 <TextBox x:Name="inputBox" Height="28" Canvas.Left="28" TextWrapping="Wrap"  Canvas.Top="21" Width="169" TextAlignment="Center" FontSize="20"
                 Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}},Path=ContentBox,Mode=TwoWay,UpdateSourceTrigger=Explicit}">



       

技術分享圖片


利用 Datacontext進行簡化的繫結: