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

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;
    }
}

转载于:https://www.cnblogs.com/sjqq/p/7806691.html

WPF中的数据绑定Data Binding使用小结相关推荐

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

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

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

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

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

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

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

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

  5. 五:Angular 数据绑定 (Data Binding)

    通常来说,数据绑定要么是从页面流向组件中的数据,要么是从组件中的数据流向页面.下面我们来介绍在Angular 2中数据绑定的几种不同方式.  1. 使用{{}}将组件中的数据显示在html页面上  实 ...

  6. WPF入门教程系列十六——WPF中的数据绑定(二)

    三.绑定模式 通过上一文章中的示例,学习了简单的绑定方式.在这里的示例,要学习一下绑定的模式,和模式的使用效果. 首先,我们来做一个简单示例,这个示例是根据ListBox中的选中项,去改变TextBl ...

  7. WPF中的Data Binding调试指南

    点击蓝字"大白技术控"关注我哟 加个"星标★",每日良时,好文必达! WPF中的Data Binding如何Debug? 大家平时做WPF开发,相信用Visua ...

  8. 数据绑定(Binding)

    Windows Presentation Foundation (WPF) 中的数据绑定为应用程序提供了一种简单.一致的数据表示和交互方法.元素能够以公共语言运行时 (CLR) 对象和 XML 形式绑 ...

  9. angular绑定数据_Angular中的数据绑定说明

    angular绑定数据 数据绑定 (Data Binding) 动机 (Motivation) Data often defines the look of an application. Inter ...

最新文章

  1. 7-5 符号配对 (20 分)
  2. 西安python培训班多少钱-西安Python培训班哪个好
  3. 超简单的话解释C#事件-源码示例
  4. Cocoa之NSWindow常用总结
  5. [YTU]_2384( 矩形类中运算符重载【C++】)
  6. ArrayList笔记
  7. 【转】编译DCMTK
  8. 计算机导论python知识点_如何系统地自学 Python?
  9. 附录 - NASMMASM 安装、部署、使用
  10. linux mysql 定时任务_Linux下Mysql定时任务备份数据的实现方法
  11. Maven 无法下载依赖包的解决方法---三步dao!!!
  12. HTML1.0 - html 环境搭建 开发工具
  13. UI设计和平面设计有什么区别哪个前景更好
  14. kasp技术原理_KASP——基因分型研究者指尖跳跃的珠链
  15. plsql oracle 使用教程
  16. BroadcastReceiver生命周期探讨
  17. smtp协议与pop3协议
  18. mysql ipv6 字段_MySQL中ipv6地址用什么类型存储?
  19. 进阶篇:4.1)DFA设计指南:简化产品设计(kiss原则)
  20. 查询同名同性学生名单,并统计同名人数

热门文章

  1. word-break:break-all和word-wrap:break-word的区别
  2. Webpack基础之输出
  3. js保留两位小数的函数_使用率低但功能强大的6个Excel函数公式应用技巧解读!...
  4. 实现点击按钮复制文本(Clipboard包)
  5. Windows 2008 R2阿里云安全基线检查
  6. idea中lombok的使用
  7. unity之中级工程师
  8. NOIP2011提高组day2
  9. numpy细碎知识点
  10. HDU 5617 Jam's maze dp+滚动数组