WPF中的数据绑定Data Binding使用小结
完整的数据绑定的语法说明可以在这里查看:
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使用小结的更多相关文章
- WPF中的数据绑定
WPF中的数据绑定 基础概念 System.Windows.Data.Binding,他会把两个对象(UI对象与UI对象之间,UI对象与.NET数据对象之间)按照指定的方式粘合在一起,并在他们之间建立 ...
- WPF入门教程系列十五——WPF中的数据绑定(一)
使用Windows Presentation Foundation (WPF) 可以很方便的设计出强大的用户界面,同时 WPF提供了数据绑定功能.WPF的数据绑定跟Winform与ASP.NET中的数 ...
- WPF中的数据绑定!!!
引用自:https://msdn.microsoft.com/zh-cn/magazine/cc163299.aspx 数据点: WPF 中的数据绑定 数据点 WPF 中的数据绑定 John Pap ...
- WPF中的数据绑定(初级)
关于WPF中的数据绑定,初步探讨 数据绑定属于WPF中比较核心的范畴,以下是对WPF中数据绑定的一个初步探讨.个人感觉还是带有问题性质的叙述比较高效,也比较容易懂 第一,什么是数据绑定? 假定有这么一 ...
- Windows Presentation Foundation(WPF)中的数据绑定(使用XmlDataProvider作控件绑定)
原文:Windows Presentation Foundation(WPF)中的数据绑定(使用XmlDataProvider作控件绑定) ------------------------------ ...
- 【值转换器】 WPF中Image数据绑定Icon对象
原文:[值转换器] WPF中Image数据绑定Icon对象 这是原来的代码: <Image Source="{Binding MenuIcon}" ...
- WPF QuickStart系列之数据绑定(Data Binding)
这篇博客将展示WPF DataBinding的内容. 首先看一下WPF Data Binding的概览, Binding Source可以是任意的CLR对象,或者XML文件等,Binding Targ ...
- WPF之数据绑定Data Binding
一般情况下,应用程序会有三层结构:数据存储层,数据处理层(业务逻辑层),数据展示层(UI界面). WPF是“数据驱动UI”. Binding实现(通过纯C#代码) Binding分为source和ta ...
- 【翻译】WPF中的数据绑定表达式
有很多文章讨论绑定的概念,并讲解如何使用StaticResources和DynamicResources绑定属性.这些概念使用WPF提供的数据绑定表达式.在本文中,让我们研究WPF提供的不同类型的数据 ...
随机推荐
- python 序列化之pickle模块 json模块
一 pickle import pickle s='dd' print(pickle.dumps(s)) 输出: b'\x80\x03X\x02\x00\x00\x00ddq\x00.' pickle ...
- Django时区配置:有次发现缓存的时间总是有问题,原来是时区配置需要改
# LANGUAGE_CODE = 'en-us' # TIME_ZONE = 'UTC' LANGUAGE_CODE = 'zh-Hans' TIME_ZONE = 'Asia/Shanghai'
- linux-3.2.36内核启动1-启动参数(arm平台 启动参数的获取和处理,分析setup_arch)【转】
转自:http://blog.csdn.net/tommy_wxie/article/details/17093297 最近公司要求调试一个内核,启动时有问题,所以就花了一点时间看看内核启动. 看的过 ...
- macOS(Sierra 10.12)上Android源码(AOSP)的下载、编译与导入到Android Studio
@import url(http://i.cnblogs.com/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/c ...
- PHP解码Json(json_decode)字符串返回NULL的原因及解决方法(转载)
本文主要为大家讲解了php在使用json_decode函数解码json字符串时,解码不成功返回NULL的问题原因分析和解决方法,感兴趣的同学参考下. 一般来说,php对json字符串解码使用json_ ...
- Lucene.net站内搜索-最简单搜索引擎代码
Lucene.Net核心类简介 先运行写好的索引的代码,再向下讲解各个类的作用,不用背代码. (*)Directory表示索引文件(Lucene.net用来保存用户扔过来的数据的地方)保存的地方,是抽 ...
- fread函数和fwrite函数
1.函数功能 用来读写一个数据块. 2.一般调用形式 fread(buffer,size,count,fp); fwrite(buffer,size,count,fp); 3.说明 ( ...
- Wireshark如何选择多行
Wireshark如何选择多行 在Wireshark中,用户经常需要选择几行,然后进行批量操作,如导出或者分析.但Wireshark没有提供通过鼠标直接选择多行的功能.这个时候,用户需要采用标记分 ...
- Xamarin.Forms的ActivityIndicator和ProgressBar比较
Xamarin.Forms的ActivityIndicator和ProgressBar比较 在Xamarin.Forms中,控件ActivityIndicator和ProgressBar都用来表示 ...
- mybatis-plus generator template 中的全部属性
{ "date": "2018-10-30", "superServiceImplClassPackage": "com.baom ...