完整的数据绑定的语法说明可以在这里查看:

http://www.nbdtech.com/Free/WpfBinding.pdf

MSDN资料:

Data Binding: Part 1 http://msdn.microsoft.com/en-us/library/aa480224.aspx

Data Binding: Part 2 http://msdn.microsoft.com/en-us/library/aa480226.aspx

Data Binding Overview http://msdn.microsoft.com/en-us/library/ms752347.aspx

INotifyPropertyChanged接口   绑定的数据源对象一般都要实现INotifyPropertyChanged接口。

{Binding}  说明了被绑定控件的属性的内容与该控件的DataContext属性关联,绑定的是其DataContext代表的整个控件的内容。如下:
<ContentControl Name="LongPreview" Grid.Row="2" Content="{Binding}" HorizontalAlignment="Left"/>
ContentControl 只是一个纯粹容纳所显示内容的一个空控件,不负责如何具体显示各个内容,借助于DataTemplate可以设置内容的显示细节。

     使用参数Path

(使用父元素的DataContext)使用参数绑定,且在数值变化时更新数据源。(两种写法)

  1. <TextBox Text="{Binding Path=Name, UpdateSourceTrigger=PropertyChanged}"/>
  2. <TextBox.Text>
  3. <Binding Path="StartPrice" UpdateSourceTrigger="PropertyChanged"/>
  4. </TextBox.Text>

相对资源RelativeSource

RelativeSource={RelativeSource Self}是一个特殊的绑定源,表示指向当前元素自己。自己绑定自己,将ToolTip属性绑定到Validation.Errors中第一个错误项的错误信息(Validation.Errors)[0].ErrorContent。

  1.  
  2. <Style x:Key="textStyleTextBox" TargetType="{x:Type TextBox}">
  3. <Setter Property="Foreground" Value="#333333" />
  4. <Setter Property="MaxLength" Value="40" />
  5. <Setter Property="Width" Value="392" />
  6. <Style.Triggers>
  7. <Trigger Property="Validation.HasError" Value="true">
  8. <Setter Property="ToolTip"
  9. Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/>
  10. </Trigger>
  11. </Style.Triggers>
  12. </Style>

使用转换器和验证规则

  1.  
  2. <TextBox Name="StartDateEntryForm" Grid.Row="3" Grid.Column="1" Style="{StaticResource textStyleTextBox}" Margin="8,5,0,5" Validation.ErrorTemplate="{StaticResource validationTemplate}">
  3. <TextBox.Text>
  4. <Binding Path="StartDate" UpdateSourceTrigger="PropertyChanged" Converter="{StaticResource dateConverter}">
  5. <Binding.ValidationRules>
  6. <src:FutureDateRule/>
  7. </Binding.ValidationRules>
  8. </Binding>
  9. </TextBox.Text>
  10. </TextBox>
  11.  
  12. //自定义的验证规则须从ValidationRule继承。
  13. class FutureDateRule : ValidationRule
  14. {
  15. public override ValidationResult Validate(object value, CultureInfo cultureInfo)
  16. {
  17. DateTime date;
  18. try
  19. {
  20. date = DateTime.Parse(value.ToString());
  21. }
  22. catch (FormatException)
  23. {
  24. return new ValidationResult(false, "Value is not a valid date.");
  25. }
  26. if (DateTime.Now.Date > date)
  27. {
  28. return new ValidationResult(false, "Please enter a date in the future.");
  29. }
  30. else
  31. {
  32. return new ValidationResult(true, null);
  33. }
  34. }
  35. }

使用数据触发器

SpecialFeatures是一个枚举数据类型。

  1.  
  2. <DataTrigger Binding="{Binding Path=SpecialFeatures}">
  3. <DataTrigger.Value>
  4. <src:SpecialFeatures>Color</src:SpecialFeatures>
  5. </DataTrigger.Value>
  6. <Setter Property="BorderBrush" Value="DodgerBlue" TargetName="border" />
  7. <Setter Property="Foreground" Value="Navy" TargetName="descriptionTitle" />
  8. <Setter Property="Foreground" Value="Navy" TargetName="currentPriceTitle" />
  9. <Setter Property="BorderThickness" Value="3" TargetName="border" />
  10. <Setter Property="Padding" Value="5" TargetName="border" />
  11. </DataTrigger>

    多重绑定

绑定源是多个源,绑定目标与绑定源是一对多的关系。

  1.  
  2. <ComboBox.IsEnabled>
  3. <MultiBinding Converter="{StaticResource specialFeaturesConverter}">
  4. <Binding Path="CurrentUser.Rating" Source="{x:Static Application.Current}"/>
  5. <Binding Path="CurrentUser.MemberSince" Source="{x:Static Application.Current}"/>
  6. </MultiBinding>
  7. </ComboBox.IsEnabled>
  8. //自定义的转换器须实现IMultiValueConverter接口。
  9. class SpecialFeaturesConverter : IMultiValueConverter
  10. {
  11. public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  12. {
  13. //数组中的对象数值的索引顺序与XAML文件的多重绑定定义有关。
  14. int rating = (int)values[0];
  15. DateTime date = (DateTime)values[1];
  16.  
  17. return ((rating >= 10) && (date.Date < (DateTime.Now.Date - new TimeSpan(365, 0, 0, 0))));
  18. }
  19.  
  20. public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
  21. {
  22. return new object[2] { Binding.DoNothing, Binding.DoNothing };
  23. }
  24. }

    Master-Detail:主-从应用(使用CollectionViewSource)

  1. 主从应用

说明:
AuctionItems的定义为:public ObservableCollection<AuctionItem> AuctionItems  。
在 ListBox 中直接使用 CollectionViewSource 来表示主数据(AuctionItem集合),在 ContentControl 中则同时使用设定 Content 和 ContentControl 两个属性, Content 直接指向CollectionViewSource, ContentControl 则使用先前已经定义的数据模板绑定(数据模板中的数据项则是绑定到AuctionItem类的各个属性)。

     数据分组(使用CollectionViewSource)
分组表头项的数据模板:
<DataTemplate x:Key="groupingHeaderTemplate">
    <TextBlock Text="{Binding Path=Name}" Foreground="Navy" FontWeight="Bold" FontSize="12" />
</DataTemplate>
在ListBox中使用分组:
<ListBox Name="Master" Grid.Row="2" Grid.ColumnSpan="3" Margin="8" ItemsSource="{Binding Source={StaticResource listingDataView}}">
    <ListBox.GroupStyle>
        <GroupStyle HeaderTemplate="{StaticResource groupingHeaderTemplate}"/>
    </ListBox.GroupStyle>
</ListBox>
分组开关:
<CheckBox Name="Grouping" Grid.Row="1" Grid.Column="0" Margin="8" Style="{StaticResource checkBoxStyle}" Checked="AddGrouping" Unchecked="RemoveGrouping">Group by category</CheckBox>
CheckBox的事件处理:
private void AddGrouping(object sender, RoutedEventArgs e)
{
    PropertyGroupDescription pgd = new PropertyGroupDescription();
    pgd.PropertyName = "Category"; //使用属性Category的数值来分组
    listingDataView.GroupDescriptions.Add(pgd);
}
private void RemoveGrouping(object sender, RoutedEventArgs e)
{
    listingDataView.GroupDescriptions.Clear();
}

     排序数据(使用CollectionViewSource) 比分组简单
排序开关:
<CheckBox Name="Sorting" Grid.Row="1" Grid.Column="3" Margin="8" Style="{StaticResource checkBoxStyle}" Checked="AddSorting" Unchecked="RemoveSorting">Sort by category and date</CheckBox>
CheckBox的事件处理:
private void AddSorting(object sender, RoutedEventArgs e)
{
    listingDataView.SortDescriptions.Add(new SortDescription("Category", ListSortDirection.Ascending));
    listingDataView.SortDescriptions.Add(new SortDescription("StartDate", ListSortDirection.Descending));
}
private void RemoveSorting(object sender, RoutedEventArgs e)
{
    listingDataView.SortDescriptions.Clear();
}

     过滤数据(使用CollectionViewSource) 跟排序类似
过滤开关:
<CheckBox Name="Filtering" Grid.Row="1" Grid.Column="1" Margin="8" Style="{StaticResource checkBoxStyle}" Checked="AddFiltering" Unchecked="RemoveFiltering">Show only bargains</CheckBox>
CheckBox的事件处理:
private void AddFiltering(object sender, RoutedEventArgs e)
{
    listingDataView.Filter += new FilterEventHandler(ShowOnlyBargainsFilter);
}
private void RemoveFiltering(object sender, RoutedEventArgs e)
{
    listingDataView.Filter -= new FilterEventHandler(ShowOnlyBargainsFilter);
}
private void ShowOnlyBargainsFilter(object sender, FilterEventArgs e)
{
    AuctionItem product = e.Item as AuctionItem;
    if (product != null)
    {
        //设置e.Accepted的值即可
        e.Accepted = product.CurrentPrice < 25;
    }
}

WPF中的数据绑定Data Binding使用小结的更多相关文章

  1. WPF中的数据绑定

    WPF中的数据绑定 基础概念 System.Windows.Data.Binding,他会把两个对象(UI对象与UI对象之间,UI对象与.NET数据对象之间)按照指定的方式粘合在一起,并在他们之间建立 ...

  2. WPF入门教程系列十五——WPF中的数据绑定(一)

    使用Windows Presentation Foundation (WPF) 可以很方便的设计出强大的用户界面,同时 WPF提供了数据绑定功能.WPF的数据绑定跟Winform与ASP.NET中的数 ...

  3. WPF中的数据绑定!!!

    引用自:https://msdn.microsoft.com/zh-cn/magazine/cc163299.aspx  数据点: WPF 中的数据绑定 数据点 WPF 中的数据绑定 John Pap ...

  4. WPF中的数据绑定(初级)

    关于WPF中的数据绑定,初步探讨 数据绑定属于WPF中比较核心的范畴,以下是对WPF中数据绑定的一个初步探讨.个人感觉还是带有问题性质的叙述比较高效,也比较容易懂 第一,什么是数据绑定? 假定有这么一 ...

  5. Windows Presentation Foundation(WPF)中的数据绑定(使用XmlDataProvider作控件绑定)

    原文:Windows Presentation Foundation(WPF)中的数据绑定(使用XmlDataProvider作控件绑定) ------------------------------ ...

  6. 【值转换器】 WPF中Image数据绑定Icon对象

    原文:[值转换器] WPF中Image数据绑定Icon对象        这是原来的代码:        <Image Source="{Binding MenuIcon}" ...

  7. WPF QuickStart系列之数据绑定(Data Binding)

    这篇博客将展示WPF DataBinding的内容. 首先看一下WPF Data Binding的概览, Binding Source可以是任意的CLR对象,或者XML文件等,Binding Targ ...

  8. WPF之数据绑定Data Binding

    一般情况下,应用程序会有三层结构:数据存储层,数据处理层(业务逻辑层),数据展示层(UI界面). WPF是“数据驱动UI”. Binding实现(通过纯C#代码) Binding分为source和ta ...

  9. 【翻译】WPF中的数据绑定表达式

    有很多文章讨论绑定的概念,并讲解如何使用StaticResources和DynamicResources绑定属性.这些概念使用WPF提供的数据绑定表达式.在本文中,让我们研究WPF提供的不同类型的数据 ...

随机推荐

  1. 两个VLC实现播放串流测试 (转)

    实现原理: 一个VLC打开视频文件发布串流(格式HTTP.RTP.RTSP等),另一个VLC打开串流播放 发布串流步骤: 1.菜单“媒体”->“流”,先添加视频文件.选择“串流”,如下图: 2. ...

  2. 32深入理解C指针之---字符串操作

    一.字符串操作主要包括字符串复制.字符串比较和字符串拼接 1.定义:字符串复制strcpy,字符串比较strcmp.字符串拼接strcat 2.特征: 1).必须包含头文件string.h 2).具体 ...

  3. 變更 cut-off,termination current,截止電流 對 battery capacity 的影響

    依之前的經驗 2700mAh 電池 cut-off 由 128 降至 64 mA,充電時間延長 20 分鐘, (128 + 64)/2 = 96 取平均充電流, 96 * (20/60) = 32 m ...

  4. 使用 IntelliJ IDEA 开发 Android 应用程序时配置 Allatori 进行代码混淆

    IntelliJ IDEA 提供了非常强大的 Android 开发支持,就连 Google 官方推荐的 Android Studio 其实也是 IntelliJ IDEA 的一个 Android 开发 ...

  5. centos 7安装postgresql10.3

    最新版本安装请移步:阿里云服务器 centos 7 安装postgresql 11 一.Postgresql简介 官方网站:https://www.postgresql.org/ 简介参考zhihu文 ...

  6. win7dos删除文件和删除文件夹

    如果要删除呢?也简单:假设删除d盘下的123文件夹 del/s/q d:\123\*.* ----(用于删除文件夹下的子文件) rd/s/q d:\123 ----(用于删除文件夹) /s参数为子目录 ...

  7. Codeforces Gym101502 H.Eyad and Math-换底公式

    H. Eyad and Math   time limit per test 2.0 s memory limit per test 256 MB input standard input outpu ...

  8. 2013 ACM/ICPC 亚洲区 杭州站

    题目链接  2013杭州区域赛 Problem A Problem B 这题我用的是SPFA+ mask dp 首先跑5次SPFA: 1次是求出每个起点和其他所有点的最短距离 4次是求出每个输入的点和 ...

  9. 死磕 java同步系列之AQS起篇

    问题 (1)AQS是什么? (2)AQS的定位? (3)AQS的实现原理? (4)基于AQS实现自己的锁? 简介 AQS的全称是AbstractQueuedSynchronizer,它的定位是为Jav ...

  10. java并发之hashmap源码

    在上篇博客中分析了hashmap的用法,详情查看java并发之hashmap 本篇博客重点分析下hashmap的源码(基于JDK1.8) 一.成员变量 HashMap有以下主要的成员变量 /** * ...