簡介:
1.WPF綁定使用的源屬性必須是依賴項屬性,這是因為依賴項屬性具有內置的更改通知支持,元素綁定表達式使用了Xaml擴展標記,
WPF綁定一個控件是使用Binding.ElementName,
綁定非控件對象時使用Source,RelativeSource,DataContext屬性(WPF特有,而非XAML),只能綁定對象的公有字段.
下邊是部分Binding 屬性名,完整列表參考 :http://msdn.microsoft.com/zh-cn/library/vstudio/ms750413.aspx
① Source:數據提供者
② RelativeSource:根據當前對象為基礎,自動查找源并綁定
③ DataContext:如果未使用Source和RelativeSource,WPF就從當前控件開始在控件樹種向上查找,并使用第一個非空的DataContext屬性,可以在更高層次容器對象上設置DataContext,如下代碼 Text 綁定到 Source屬性,但未設置Text的綁定對象,會向上查找DataContext綁定的對象的Source屬性
實例:
<Grid><StackPanel DataContext="{x:Static SystemFonts.IconFontFamily}"><TextBox Margin="5" Text="{Binding Path=Source,Mode=OneWay}"></TextBox></StackPanel><ComboBox x:Name="lstColors" Margin="3,43,189,196"><ComboBoxItem Content="Red" HorizontalAlignment="Left" Width="224"/><ComboBoxItem Content="Green" HorizontalAlignment="Left" Width="224"/><ComboBoxItem Content="Blue" HorizontalAlignment="Left" Width="224"/></ComboBox><TextBlock Margin="3,117,3,3" x:Name="lblSampleText"Text="{Binding ElementName=lstColors,Path=SelectedItem.Content}"Background="{Binding ElementName=lstColors,Path=SelectedItem.Content}" ></TextBlock> </Grid>
實例2,使用代碼實現綁定:
//使用代碼創建綁定 Binding binding = new Binding(); binding.Source = System.Diagnostics.Process.GetCurrentProcess(); binding.Path = new PropertyPath("ProcessName"); binding.Mode = BindingMode.OneWay; txtOne.SetBinding(TextBlock.TextProperty,binding); //Path中使用"."標識當前數據源 Binding binding2 = new Binding(); binding2.Source = SystemColors.ActiveBorderBrush; binding2.Path = new PropertyPath("."); txtOne.SetBinding(TextBlock.BackgroundProperty, binding2);
2.BindingMode的枚舉值有:
① OneWay
② TwoWay
③ OneTime:根據源端屬性值設置目標屬性值,之后的改變會被忽略,除非調用BindingExpression.UpdateTarge方法
④ OneWayToSource:與OneWay類似,但方向相反,用于目標屬性是非依賴項屬性的情況
⑤ Default:默認值,根據目標屬性確定綁定類型.依賴項屬性都由一個元數據 FrameworkPropertyMetadata.BindsTwoWayByDefault用于標識oneway綁定還是twoway綁定
3.從目標到綁定源端數據更新時(binding mode為twoway或者onewaytosource),更新行為(什么時機更新)由Binding.UpdateSourceTrigger枚舉屬性控制,UpdateSourceTrigger的值有:
① PropertyChanged:目標屬性發生變化時立即更新
② LostFocus:目標屬性發生變化并且目標丟失焦點時更新源
③ Explicit:除非調用BindingExpression.UpdateSource()方法,否則無法更新
④ Default:根據目標屬性的元數據(FrameworkPropertMetadata.DefaulUpdateSourceTrigger)確定更新行為,大多數屬性默認行為是PropertyChanged
4.WPF中派生自ItemsControl的類都能顯示列表,能夠支持集合數據綁定的元素包括ListBox,ComboBox,ListView和DataGrid,Menu,Treeview,ItemsControl中有三個重要屬性:
① ItemsSource: 指向一個集合,結合必須支持IEnumerable接口,該集合包含將在列表中顯示的所有元素,但基本的IEnumerable接口只支持只讀綁定,要使修改能直接反應到綁定的控件上需要使用ObservablCollection類
② DisplayMemberPath:確定用于顯示的 對象的屬性,如果未設置 則會顯示對象的ToString()方法返回的值
③ ItemTemplates:接受一個數據模板,用于為每個項創建可視化外觀
?