添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
爱搭讪的蚂蚁  ·  WPF 和 Windows Forms ...·  3 月前    · 
沉稳的围巾  ·  博客导航 - lindexi ·  1 月前    · 
睡不着的跑步鞋  ·  WPF RadGridView ...·  3 周前    · 
坚强的眼镜  ·  WPF Datagrid ...·  3 周前    · 

Introduction

在应用了MVVM设计模式的情况下,Data Binding特别常见。因为我们需要通过它来将前后端分离,让UI的归UI,业务归业务。

所谓Data Binding,就是将数据源中的某些信息赋给目标对象的某个属性。目标对象的这个属性必须是dependency property。因为dependency property原生支持change notification。而数据源的类型就没有什么限制。

四类绑定形式

从数据来源来分类,可以把绑定分成四类形式

  • 来自于WPF Element
  • 来自于Source 对象
  • 来自于Relative Source对象
  • 来自于DataContext
  • 1. 来自于WPF Element

    <Slider Name="FontSizeSlider" Minimum="1" Maximum="40" Value="10" TickFrequency="1" />
    <TextBlock FontSize="{Binding ElementName=FontSizeSlider, Path=Value}" />
    

    我们可以直接通过 ElementName来指向引用的界面元素。

    2. 来自于Source对象

    一般用来绑定静态资源,比如

    <Window.Resources>
    	<FontFamily x:Key="CustomFont">Calibri</FontFamily>
    </Window.Resources>
    <TextBlock Text="{Binding Source={StaticResource CustomFont}, Path=Source}"/>
    

    3. 来自于Relative Source对象

    这种绑定形式稍微复杂。Relative Source绑定有四个模式

    3-1. Self

    引用本身的另一个属性。比如

    <CheckBox ...... CommandParameter="{Binding RelativeSource={RelativeSource Self},Path=IsChecked}" />
    

    3-2. FindAncestor

    引用祖先的一个属性。祖先在这里指在element tree上的祖先。说白了,就是当前节点的父节点或者爷爷节点,以此类推。

    在指定寻找祖先的策略时,有两个属性我们需要指定。一个是AncestorType,另一个是AncestorLevel。前者表明了我们要寻找的类型,后者帮助我们跳过不相干的祖先的同类。(AncestorLevel默认为 1,也就是寻找最近的祖先)。

    <TextBlock Text="{Binding Path=Title,
    		RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}} }" />
    

    3-3. TemplatedParent

    一般用在control template或者data template中,用来引用template的父控件内的属性。

    3-4. PreviousData

    不常用,skip。

    4. 来自于DataContext

    这是在MVVM下,最常见的一种绑定,它的好处在于父控件指定了DataContext后,其子控件都能直接绑定DataContext中的属性。

    一般我们都将DataContext绑定到我们自定的ViewModel,从而将数据和其表现形式分离。

    <Window ...>
        <Window.DataContext>
            <local:MyViewModel />
        </Window.DataContext>
    	<StackPanel>
    		<WrapPanel>
    			<TextBlock Text="Window title:  " />
    			<TextBox Text="{Binding Title, UpdateSourceTrigger=PropertyChanged}" Width="150" />
    		</WrapPanel>
    		<WrapPanel Margin="0,10,0,0">
    			<TextBlock Text="Window dimensions: " />
    			<TextBox Text="{Binding Width}" Width="50" />
    			<TextBlock Text=" x " />
    			<TextBox Text="{Binding Height}" Width="50" />
    		</WrapPanel>
    	</StackPanel>
    </Window>
    
    public class MyViewModel {
        public string Title {get;set;}
        public int Width {get;set;}
        public int Height {get;set;}
    

    以上就是WPF中所有的Data Binding的类型。

    (end.)