[源码下载]

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

作者:webabcd

介绍
背水一战 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(, ).ToString().PadLeft(, '') };
} 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() 显示触发
*
*
* 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

<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"/>
<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()[];
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
[源码下载]

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

  1. 绑定: DataContextChanged, UpdateSourceTrigger, 对绑定的数据做自定义转换

    介绍背水一战 Windows 10 之 绑定 DataContextChanged - FrameworkElement 的 DataContext 发生变化时触发的事件 UpdateSourceTr ...

  2. 背水一战 Windows 10 (21) - 绑定: x:Bind 绑定, x:Bind 绑定之 x:Phase, 使用绑定过程中的一些技巧

    [源码下载] 背水一战 Windows 10 (21) - 绑定: x:Bind 绑定, x:Bind 绑定之 x:Phase, 使用绑定过程中的一些技巧 作者:webabcd 介绍背水一战 Wind ...

  3. 背水一战 Windows 10 (22) - 绑定: 通过 Binding 绑定对象, 通过 x:Bind 绑定对象, 通过 Binding 绑定集合, 通过 x:Bind 绑定集合

    [源码下载] 背水一战 Windows 10 (22) - 绑定: 通过 Binding 绑定对象, 通过 x:Bind 绑定对象, 通过 Binding 绑定集合, 通过 x:Bind 绑定集合 作 ...

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

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

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

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

  6. 背水一战 Windows 10 (24) - MVVM: 通过 Binding 或 x:Bind 结合 Command 实现,通过非 ButtonBase 触发命令

    [源码下载] 背水一战 Windows 10 (24) - MVVM: 通过 Binding 或 x:Bind 结合 Command 实现,通过非 ButtonBase 触发命令 作者:webabcd ...

  7. 背水一战 Windows 10 (75) - 控件(控件基类): FrameworkElement - 基础知识, 相关事件, HorizontalAlignment, VerticalAlignment

    [源码下载] 背水一战 Windows 10 (75) - 控件(控件基类): FrameworkElement - 基础知识, 相关事件, HorizontalAlignment, Vertical ...

  8. 背水一战 Windows 10 (35) - 控件(弹出类): FlyoutBase, Flyout, MenuFlyout

    [源码下载] 背水一战 Windows 10 (35) - 控件(弹出类): FlyoutBase, Flyout, MenuFlyout 作者:webabcd 介绍背水一战 Windows 10 之 ...

  9. 背水一战 Windows 10 (32) - 控件(选择类): Selector, ComboBox

    [源码下载] 背水一战 Windows 10 (32) - 控件(选择类): Selector, ComboBox 作者:webabcd 介绍背水一战 Windows 10 之 控件(选择类) Sel ...

随机推荐

  1. Python黑帽编程1.1虚拟机安装和配置 Kali Linux 2016

    Python黑帽编程1.1虚拟机安装和配置 Kali Linux 2016 0.1  本系列教程说明 本系列教程,采用的大纲母本为<Understanding Network Hacks Att ...

  2. JWS.Mono如何进行“在线安装”

    这里话就不多说了,使用方法如下: wget http://jhonge.net/down4load/1413998270361/jwsmono_net.sh chmod a+x jwsmono_net ...

  3. jQuery编程的最佳实践

    好像是feedly订阅里看到的文章,读完后觉得非常不错,译之备用,多看受益. 加载jQuery 1.坚持使用CDN来加载jQuery,这种别人服务器免费帮你托管文件的便宜干嘛不占呢.点击查看使用CDN ...

  4. [转]GC简介

    [转]GC简介 原文链接:http://www.cnblogs.com/cposture/p/4845189.html 原文写得太好了,这里转一下. 1 GC机制 1.1 对象 从计算机的角度,装有数 ...

  5. Tomcat7基于Redis的Session共享实战二

    目前,为了使web能适应大规模的访问,需要实现应用的集群部署.集群最有效的方案就是负载均衡,而实现负载均衡用户每一个请求都有可能被分配到不固定的服务器上,这样我们首先要解决session的统一来保证无 ...

  6. 如何用注解简化SSH框架

    一.简化代码第一步,删除映射文件,给实体类加上注解 @Entity //声明当前类为hibernate映射到数据库中的实体类 @Table(name="news") //声明tab ...

  7. java IO流 之 字符流

    字符是我们能读懂的一些文字和符号,但在计算机中存储的却是我们看不懂的byte 字节,那这就存在关于字符编码解码的问题.所以在学习Io流的字符流前我们先了解些关于编码问题. 一.字符集与字符编码 1.什 ...

  8. MongoDB 文档的查询和插入操作

    MongoDB是文档型数据库,有一些专门的术语,和关系型DB相似,但也有差异,例如,Collection类似于关系型DB的Table,document类似于row,key/value pair类似于c ...

  9. Undo/Redo for Qt Tree Model

    Undo/Redo for Qt Tree Model eryar@163.com Abstract. Qt contains a set of item view classes that use ...

  10. eclipse将android项目生成apk并且给apk签名

    转载:http://www.cnblogs.com/tianguook/archive/2012/09/27/2705724.html 生成apk最懒惰的方法是:只要你运行过android项目,到工作 ...