介绍
背水一战 Windows 10 之 绑定

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

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

<Page
x: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

<Page
x: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() 显示触发
*/ 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 void btnBinding_Click(object sender, RoutedEventArgs e)
{
// 显示触发 txtExplicit 的数据更新
BindingExpression be = txtExplicit.GetBindingExpression(TextBox.TextProperty);
be.UpdateSource();
}
}
}

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

<Page
x: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"/>
</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" TextWrapping="Wrap" /> </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;
}
}
}

绑定: DataContextChanged, UpdateSourceTrigger, 对绑定的数据做自定义转换的更多相关文章

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

    [源码下载] 背水一战 Windows 10 (20) - 绑定: DataContextChanged, UpdateSourceTrigger, 对绑定的数据做自定义转换 作者:webabcd 介 ...

  2. 重新想象 Windows 8.1 Store Apps (82) - 绑定: DataContextChanged, TargetNullValue, FallbackValue, UpdateSourceTrigger

    [源码下载] 重新想象 Windows 8.1 Store Apps (82) - 绑定: DataContextChanged, TargetNullValue, FallbackValue, Up ...

  3. WPF的DataGrid绑定ItemsSource后第一次加载数据有个别列移位的解决办法

    最近用WPF的DataGrid的时候,发现一个很弱智的问题,DataGrid的ItemsSource是绑定了一个属性: 然后取数给这个集合赋值的时候,第一次赋值,就会出现列移位 起初还以为是显卡的问题 ...

  4. SpringMVC参数绑定学习总结【前后端数据参数传递】

    目录 1. 绑定机制 2. 支持的数据类型 3. 参数请求中文乱码解决 4.自定义类型转换器 5.最后参数绑定学习小结 SpringMVC作为Controller层(等价servlet和struts中 ...

  5. 关于mvvm:UI、数据、绑定、状态、中间变量、数据适配、数据处理

    绑定: UI控件 --> VM    VM -> UI控件 关于mvvm:UI.数据.绑定.状态.中间变量.数据适配.数据处理: https://github.com/zzf073/Log ...

  6. 使用进程池模拟多进程爬取url获取数据,使用进程绑定的回调函数去处理数据

    1 # 使用requests请求网页,爬取网页的内容 2 3 # 模拟使用进程池模拟多进程爬取网页获取数据,使用进程绑定的回调函数去处理数据 4 5 import requests 6 from mu ...

  7. 重新开始学习javase_多态(动态绑定、推迟绑定或者运行期绑定)

    一,谈向上转换,或者上溯造型 什么是向上转换(上溯造型),一句话就是父类的引用指向子类的对象.或者把子类的对象当作父类来用 为什么要进行向上转换?我们先看一个例子吧! @Test public voi ...

  8. 1.面向过程编程 2.面向对象编程 3.类和对象 4.python 创建类和对象 如何使用对象 5.属性的查找顺序 6.初始化函数 7.绑定方法 与非绑定方法

    1.面向过程编程 面向过程:一种编程思想在编写代码时 要时刻想着过程这个两个字过程指的是什么? 解决问题的步骤 流程,即第一步干什么 第二步干什么,其目的是将一个复杂的问题,拆分为若干的小的问题,按照 ...

  9. 高级参数绑定(数组和List绑定)

    1.绑定数组: (1) 需求 在商品列表页面选中多个商品,然后删除. (2). 需求分析 功能要求商品列表页面中的每个商品前有一个checkbok,选中多个商品后点击删除按钮把商品id传递给Contr ...

随机推荐

  1. LESS速查

    注释 缓存式注释/*注释内容*/  非缓存式注释//注释内容 变量 @nice-blue: #5B83AD; @light-blue: @nice-blue + #111; #header { col ...

  2. 在Java代码中使用iTextPDF生成PDF

    1. 生成PDF 载入字体 static { FontFactory.register("/fonts/msyh.ttf"); FontFactory.register(" ...

  3. windows和ubuntu下gif动态图片的制作

    现在社交软件中, 各种各样的动图为大家交流很大的乐趣.  Gif图片比视频小, 比静态JPG图片形象生动, 更适用于产品展示和步骤演示等. 这里简单介绍一下在window系统和ubuntu系统下gif ...

  4. noip2016代码

    ---------------------------------------------------------------------------------- 以下均为AC代码 -------- ...

  5. poj3270

    Cow Sorting Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 6750   Accepted: 2633 Descr ...

  6. JAVA和android 环境配置

    1.设置classpath .;%JAVA_HOME%\lib\dt.jar;%JAVA_HOME\lib\tools.jar; 2.JAVA_HOME D:\Program Files\Java\j ...

  7. Ubuntu环境下安装TinyOS系统

    1.输入下面命令会弹出source list窗口   1 sudo gedit /etc.apt/sources.list 在尾部添加以下地址:   1 2 deb http://tinyos.sta ...

  8. Python2.2-原理之类型和运算

    此节来自于<Python学习手册第四版>第二部分 一.Python对象类型(第4章) 1. Python可以分解成模块.语句.表达式以及对象:1.程序由模块构成:2.模块包含语句:3.语句 ...

  9. Theano2.1.6-基础知识之在thenao中的求导

    来自:http://deeplearning.net/software/theano/tutorial/gradients.html Derivatives in Theano 一.计算梯度 现在,让 ...

  10. Apache下开启SSI配置使html支持include包含

    写页面的同学通常会遇到这样的烦恼,就是页面上的 html 标签越来越多的时候,寻找指定的部分就会很困难,那么能不能像 javascript 一样写在不同的文件中引入呢?答案是有的,apache 能做到 ...