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

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)使用参数绑定,且在数值变化时更新数据源。(两种写法)

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

相对资源RelativeSource

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


<Style x:Key="textStyleTextBox" TargetType="{x:Type TextBox}">
<Setter Property="Foreground" Value="#333333" />
<Setter Property="MaxLength" Value="40" />
<Setter Property="Width" Value="392" />
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>

使用转换器和验证规则


<TextBox Name="StartDateEntryForm" Grid.Row="3" Grid.Column="1" Style="{StaticResource textStyleTextBox}" Margin="8,5,0,5" Validation.ErrorTemplate="{StaticResource validationTemplate}">
<TextBox.Text>
<Binding Path="StartDate" UpdateSourceTrigger="PropertyChanged" Converter="{StaticResource dateConverter}">
<Binding.ValidationRules>
<src:FutureDateRule/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox> //自定义的验证规则须从ValidationRule继承。
class FutureDateRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
DateTime date;
try
{
date = DateTime.Parse(value.ToString());
}
catch (FormatException)
{
return new ValidationResult(false, "Value is not a valid date.");
}
if (DateTime.Now.Date > date)
{
return new ValidationResult(false, "Please enter a date in the future.");
}
else
{
return new ValidationResult(true, null);
}
}
}

使用数据触发器

SpecialFeatures是一个枚举数据类型。


<DataTrigger Binding="{Binding Path=SpecialFeatures}">
<DataTrigger.Value>
<src:SpecialFeatures>Color</src:SpecialFeatures>
</DataTrigger.Value>
<Setter Property="BorderBrush" Value="DodgerBlue" TargetName="border" />
<Setter Property="Foreground" Value="Navy" TargetName="descriptionTitle" />
<Setter Property="Foreground" Value="Navy" TargetName="currentPriceTitle" />
<Setter Property="BorderThickness" Value="3" TargetName="border" />
<Setter Property="Padding" Value="5" TargetName="border" />
</DataTrigger>

    多重绑定

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


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

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

主从应用

说明:
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. APUE 学习笔记(四) 标准I/O库

    1.流与FILE对象 unix I/O系统调用都是针对文件描述符的 标准C的I/O函数都是针对流(文件指针)的,我们使用一个流与一个文件相关联   2.缓冲 标准I/O库提供缓冲的目的就是尽可能减少r ...

  2. Codeforces 403D: Beautiful Pairs of Numbers(DP)

    题意:转换模型之后,就是1~n个数中选k个,放到一个容量为n的背包中,这个背包还特别神奇,相同的物品摆放的位置不同时,算不同的放法(想象背包空间就是一个长度为n的数组,然后容量为1的物体放一个格子,容 ...

  3. Image与Base64String的互转换

    public Image Base64ToImage(string base64String) { // Convert Base64 String to byte[] byte[] imageByt ...

  4. HDU 5266 pog loves szh III(区间LCA)

    题目链接 pog loves szh III 题意就是  求一个区间所有点的$LCA$. 我们把$1$到$n$的$DFS$序全部求出来……然后设$i$的$DFS$序为$c[i]$,$pc[i]$为$c ...

  5. Vue开发之路由进阶

    1.路由组件传参 在一个页面中,需要根据路由获得参数,然后在页面进行逻辑处理,可以通过$route来获取相关参数 但是这样一来,页面组件与路由耦合太高,为了解耦,页面组件可以在更大程度上进行复用,可以 ...

  6. codevs——1008 选数

    1008 选数 2002年NOIP全国联赛普及组  时间限制: 1 s  空间限制: 128000 KB  题目等级 : 黄金 Gold 题解       题目描述 Description 已知 n ...

  7. Chelly的串串专题

    CF149E 题意:给出一个长度为n的文本串和m个模式串,求有多少个模式串可以拆成两半,使得这两半按顺序匹配(n<=2e5,m<=100) 最暴力的想法就是对于每个询问串,全部和原串做一遍 ...

  8. arch 安装

    xfce参考 http://my.oschina.net/u/1408707/blog/182581#OSC_h2_6 chm阅读 – chmsee作为一个苦逼的码农,要忍受各种chm文件的蹂躏,这个 ...

  9. 为Jenkins增加ssl(https)的访问支持(Windows/Linux)

    前言: 增加ssl(https)的访问可以为部署在公网下的jenkins提供更安全的问题,最明显的好处应该是登录和jenkins-ci.jar的调用. 比如jenkins-ci.jar的调用,一般在w ...

  10. iOS -- 设置label的自适应

    - (void)AutoLabel { //准备工作 self.font = [UIFont systemFontOfSize:]; self.textColor = [UIColor whiteCo ...