背水一战 Windows 10 (20) - 绑定: DataContextChanged, UpdateSourceTrigger, 对绑定的数据做自定义转换
原文:背水一战 Windows 10 (20) - 绑定: DataContextChanged, UpdateSourceTrigger, 对绑定的数据做自定义转换

[源码下载]

背水一战 Windows 10 (20) - 绑定: DataContextChanged, UpdateSourceTrigger, 对绑定的数据做自定义转换

作者:webabcd

介绍
背水一战 Windows 10 之 绑定

  • DataContextChanged - FrameworkElement 的 DataContext 发生变化时触发的事件
  • UpdateSourceTrigger - 数据更新的触发方式
  • 对绑定的数据做自定义转换

示例
1、演示 DataContextChanged 的用法
Bind/DataContextChanged.xaml

<Pagex:Class="Windows10.Bind.DataContextChanged"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:local="using:Windows10.Bind"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"mc:Ignorable="d"><Grid Background="Transparent"><StackPanel Margin="10 0 10 10"><TextBlock Name="lblMsg" Margin="5" /><Button x:Name="btnChange" Content="改变 listBox 的数据上下文" Click="btnChange_Click" Margin="5" /><ListBox x:Name="listBox" ItemsSource="{Binding}" DataContextChanged="listBox_DataContextChanged" Background="Orange" Margin="5" /></StackPanel></Grid>
</Page>

Bind/DataContextChanged.xaml.cs

/** DataContextChanged - FrameworkElement 的 DataContext 发生变化时触发的事件*/using System;
using System.Collections.Generic;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;namespace Windows10.Bind
{public sealed partial class DataContextChanged : Page{public DataContextChanged(){this.InitializeComponent();this.Loaded += DataContextChanged_Loaded;}private void DataContextChanged_Loaded(object sender, RoutedEventArgs e){// 指定数据上下文listBox.DataContext = new List<string> { "a", "b", "c" };}private void btnChange_Click(object sender, RoutedEventArgs e){// 修改数据上下文listBox.DataContext = new List<string> { "a", "b", new Random().Next(0, 1000).ToString().PadLeft(3, '0') };}private void listBox_DataContextChanged(FrameworkElement sender, DataContextChangedEventArgs args){/** FrameworkElement.DataContextChanged - 数据上下文发生改变后触发的事件*/// 数据上下文发生改变后lblMsg.Text = "数据上下文发生改变:" + DateTime.Now.ToString("hh:mm:ss");}}
}

2、演示 UpdateSourceTrigger 的用法
Bind/UpdateSourceTrigger.xaml

<Pagex:Class="Windows10.Bind.UpdateSourceTrigger"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:local="using:Windows10.Bind"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"mc:Ignorable="d"><Grid Background="Transparent"><StackPanel Margin="10 0 10 10"><TextBlock Name="lblMsg" Foreground="Orange" Margin="5" /><!--UpdateSourceTrigger - 数据更新的触发方式Default - 失去焦点后触发PropertyChanged - 属性值发生改变后触发Explicit - 需要通过 BindingExpression.UpdateSource() 显示触发--><TextBox Text="{Binding Text, Mode=TwoWay, ElementName=lblMsg, UpdateSourceTrigger=Default}" Margin="5" /><TextBox Text="{Binding Text, Mode=TwoWay, ElementName=lblMsg, UpdateSourceTrigger=PropertyChanged}" Margin="5" /><TextBox Name="txtExplicit" Text="{Binding Text, Mode=TwoWay, ElementName=lblMsg, UpdateSourceTrigger=Explicit}" Margin="5" /><Button Name="btnBinding" Content="显示触发更新" Click="btnBinding_Click" Margin="5" /></StackPanel></Grid>
</Page>

Bind/UpdateSourceTrigger.xaml.cs

/** UpdateSourceTrigger - 数据更新的触发方式*     Default - 失去焦点后触发*     PropertyChanged - 属性值发生改变后触发*     Explicit - 需要通过 BindingExpression.UpdateSource() 显示触发*     *     * BindingExpression - 绑定信息,可以通过 FrameworkElement 的 GetBindingExpression() 方法获取指定属性的绑定信息*     DataItem - 获取绑定的源对象*     ParentBinding - 获取绑定的 Binding 对象(Binding 对象里包括 ElementName, Path, Mode 等绑定信息)*     UpdateSource() - 将当前值发送到 TwoWay 绑定的源对象的绑定的属性中*/using System;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;namespace Windows10.Bind
{public sealed partial class UpdateSourceTrigger : Page{public UpdateSourceTrigger(){this.InitializeComponent();}private async void btnBinding_Click(object sender, RoutedEventArgs e){// 显示触发 txtExplicit 的数据更新BindingExpression be = txtExplicit.GetBindingExpression(TextBox.TextProperty);be.UpdateSource();// 获取绑定的相关信息Binding binding = be.ParentBinding;TextBlock textBlock = be.DataItem as TextBlock;MessageDialog messageDialog = new MessageDialog($"BindingExpression.DataItem:{textBlock.Name}, Binding.Mode:{binding.Mode}");await messageDialog.ShowAsync();}}
}

3、演示如何对绑定的数据做自定义转换
Bind/BindingConverter.xaml

<Pagex:Class="Windows10.Bind.BindingConverter"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:local="using:Windows10.Bind"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"mc:Ignorable="d"><Grid Background="Transparent"><StackPanel Margin="10 0 10 10"><!--配置 IValueConverter 资源--><StackPanel.Resources><local:IntegerLetterConverter x:Key="IntegerLetterConverter"/><local:FormatConverter x:Key="FormatConverter"/><x:String x:Key="FormatString">格式化字符串 {0}</x:String></StackPanel.Resources><Slider Name="slider1" Minimum="97" Maximum="122" Value="1" Width="300" Background="White" HorizontalAlignment="Left" Margin="5" /><!--演示如何使用 Binding 的 Converter, ConverterParameter, ConverterLanguage注:ConverterParameter 和 ConverterLanguage 不支持绑定,只能配置为一个静态的值(但是在 C# 端可以实现一些在 xaml 中无法实现的特性,详见后面的例子)--><TextBox Name="textBox1" Width="300" HorizontalAlignment="Left" Margin="5"Text="{Binding ElementName=slider1, Path=Value, Mode=TwoWay,Converter={StaticResource IntegerLetterConverter},ConverterParameter=param, ConverterLanguage=zh}" /><Slider Name="slider2" Minimum="97" Maximum="122" Value="1" Width="300" Background="White" HorizontalAlignment="Left" Margin="5" /><!--在 C# 端使用 Binding 的 Converter, ConverterParameter, ConverterLanguage--><TextBox Name="textBox2" Width="300" HorizontalAlignment="Left" Margin="5" /><TextBlock Name="lblMsg" Margin="5" TextWrapping="Wrap" /><!--演示如何在 ConverterParameter 中通过 {0} 格式化字符串 --><TextBlock Name="textBlock1" Text="我是“textBlock1”" Margin="5" /><TextBlock Name="textBlock2" Margin="5" Text="{Binding ElementName=textBlock1, Path=Text,Converter={StaticResource FormatConverter},ConverterParameter={StaticResource FormatString}}" /></StackPanel></Grid>
</Page>

Bind/BindingConverter.xaml.cs

/** 演示如何对绑定的数据做自定义转换*/using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;namespace Windows10.Bind
{public sealed partial class BindingConverter : Page{public BindingConverter(){this.InitializeComponent();this.Loaded += BindingConverter_Loaded;}private void BindingConverter_Loaded(object sender, RoutedEventArgs e){// 实例化 Binding 对象Binding binding = new Binding(){ElementName = nameof(slider2),Path = new PropertyPath(nameof(Slider.Value)),Mode = BindingMode.TwoWay, // 默认是 OneWay 的Converter = new IntegerLetterConverter(),ConverterParameter = lblMsg, // 将 ConverterParameter 设置为一个指定的控件,这个在 xaml 中实现不了,但是可以在 C# 端实现ConverterLanguage = "zh"};// 将目标对象的目标属性与指定的 Binding 对象关联
            BindingOperations.SetBinding(textBox2, TextBox.TextProperty, binding);}}// 自定义一个实现了 IValueConverter 接口的类,用于对绑定的数据做自定义转换public sealed class IntegerLetterConverter : IValueConverter{/// <summary>/// 正向转换器。将值从数据源传给绑定目标时,数据绑定引擎会调用此方法/// </summary>/// <param name="value">转换之前的值</param>/// <param name="targetType">转换之后的数据类型</param>/// <param name="parameter">转换器所使用的参数(它是通过 Binding 的 ConverterParameter 传递过来的)</param>/// <param name="language">转换器所使用的区域信息(它是通过 Binding 的 ConverterLanguage 传递过来的)</param>/// <returns>转换后的值</returns>public object Convert(object value, Type targetType, object parameter, string language){if (parameter != null && parameter.GetType() == typeof(TextBlock)){((TextBlock)parameter).Text = $"value: {value}, targetType: {targetType}, parameter: {parameter}, language: {language}";}int v = (int)(double)value;return (char)v;}/// <summary>/// 反向转换器。将值从绑定目标传给数据源时,数据绑定引擎会调用此方法/// </summary>/// <param name="value">转换之前的值</param>/// <param name="targetType">转换之后的数据类型</param>/// <param name="parameter">转换器所使用的参数(它是通过 Binding 的 ConverterParameter 传递过来的)</param>/// <param name="language">转换器所使用的区域信息(它是通过 Binding 的 ConverterLanguage 传递过来的)</param>/// <returns>转换后的值</returns>public object ConvertBack(object value, Type targetType, object parameter, string language){if (parameter != null && parameter.GetType() == typeof(TextBlock)){((TextBlock)parameter).Text = $"value: {value}, targetType: {targetType}, parameter: {parameter}, language: {language}";}int v = ((string)value).ToCharArray()[0];return v;}}// 自定义一个实现了 IValueConverter 接口的类,用于格式化字符串public sealed class FormatConverter : IValueConverter{public object Convert(object value, Type targetType, object parameter, string language){string format = (string)parameter;return string.Format(format, value);}public object ConvertBack(object value, Type targetType, object parameter, string language){throw new NotImplementedException();}}
}

OK
[源码下载]

posted on 2017-09-21 10:05 NET未来之路 阅读(...) 评论(...) 编辑 收藏

转载于:https://www.cnblogs.com/lonelyxmas/p/7567069.html

背水一战 Windows 10 (20) - 绑定: DataContextChanged, UpdateSourceTrigger, 对绑定的数据做自定义转换...相关推荐

  1. 背水一战 Windows 10 (18) - 绑定: 与 Element 绑定, 与 Indexer 绑定, TargetNullValue, FallbackValue...

    原文:背水一战 Windows 10 (18) - 绑定: 与 Element 绑定, 与 Indexer 绑定, TargetNullValue, FallbackValue [源码下载] 背水一战 ...

  2. 背水一战 Windows 10 (19) - 绑定: TemplateBinding 绑定, 与 RelativeSource 绑定, 与 StaticResource 绑定...

    原文:背水一战 Windows 10 (19) - 绑定: TemplateBinding 绑定, 与 RelativeSource 绑定, 与 StaticResource 绑定 [源码下载] 背水 ...

  3. 背水一战 Windows 10 (10) - 资源: StaticResource, ThemeResource

    原文:背水一战 Windows 10 (10) - 资源: StaticResource, ThemeResource [源码下载] 背水一战 Windows 10 (10) - 资源: Static ...

  4. 背水一战 Windows 10 (30) - 控件(文本类): AutoSuggestBox

    背水一战 Windows 10 (30) - 控件(文本类): AutoSuggestBox 原文:背水一战 Windows 10 (30) - 控件(文本类): AutoSuggestBox [源码 ...

  5. 背水一战 Windows 10 (70) - 控件(控件基类): UIElement - Transform3D(3D变换), Projection(3D投影)...

    原文:背水一战 Windows 10 (70) - 控件(控件基类): UIElement - Transform3D(3D变换), Projection(3D投影) [源码下载] 背水一战 Wind ...

  6. 背水一战 Windows 10 (55) - 控件(集合类): SemanticZoom, ISemanticZoomInformation

    原文:背水一战 Windows 10 (55) - 控件(集合类): SemanticZoom, ISemanticZoomInformation [源码下载] 背水一战 Windows 10 (55 ...

  7. 背水一战 Windows 10 (46) - 控件(ScrollViewer 基础): ScrollViewer, ScrollBar, ScrollContentPresenter...

    原文:背水一战 Windows 10 (46) - 控件(ScrollViewer 基础): ScrollViewer, ScrollBar, ScrollContentPresenter [源码下载 ...

  8. 背水一战 Windows 10 (34) - 控件(进度类): RangeBase, Slider, ProgressBar, ProgressRing

    背水一战 Windows 10 (34) - 控件(进度类): RangeBase, Slider, ProgressBar, ProgressRing 原文:背水一战 Windows 10 (34) ...

  9. 背水一战 Windows 10 (80) - 本地化

    背水一战 Windows 10 (80) - 本地化 原文: 背水一战 Windows 10 (80) - 本地化 [源码下载] 背水一战 Windows 10 (80) - 本地化 作者:webab ...

最新文章

  1. SQL Server 2005的服务器角色(public)的问题
  2. ScheduleThreadPoolExecutor的工作原理与使用示例
  3. Spring Boot怎么样处理静态资源(静态资源映射规则)_Web开发
  4. 吴恩达机器学习(第二章)——单变量线性回归
  5. c语言常量结构体的成员,c语言之结构体
  6. MySql DATE_FORMAT函数用法
  7. sockaddr类型重定义
  8. 记一次培训机构“面试”过程
  9. 洛谷—— P1847 轰炸II
  10. Anscombe's Quartet 问题
  11. linux操作系统实验目的,Linux操作系统实验报告.doc
  12. 三天研读《中兴电路设计规范》精华总结
  13. 逐梦旅程:Windows游戏编程之从零开始 读后感
  14. maven项目关于ojdbc14依赖配置
  15. 产品经理的私房菜 - 腾讯产品模型 - 学习能力篇
  16. win10的计算机用户名怎么改,win10账户名修改,教您win10怎么更改账户名称
  17. 红米越卖越贵,消费者如今总算有了新选择,魅蓝回来了
  18. 敬天爱人 大道至简——初读《经营十二条》
  19. 手机上传文件到ftp服务器,上传文件到iPhone上的FTP服务器(Upload File to FTP Server on i...
  20. 学习GAN必须阅读的10篇论文

热门文章

  1. 网易云音乐基于 Flink + Kafka 的实时数仓建设实践
  2. ​我们的系统需要什么样的分布式锁?
  3. 游戏光线追踪往事:十年技术轮回
  4. pmp每日三题(2022年3月4日)
  5. aproxy配合Nginx搭建Web集群部署实验(图文详解)
  6. THUPCCTSAPIO摸鱼被$\Huge{\color{black}{\mathbf{z}}\color{red}{\mathbf{zh}}}$爆踩记
  7. 爬虫简单入门:第一个简单爬虫
  8. 源哥每日一题第十三弹 百练4124:海贼王之伟大航路 状压dp
  9. CCF - 201503-3 - 节日
  10. Python自学之乐-Python字典实现简单的三级菜单