[源码下载]

重新想象 Windows 8 Store Apps (52) - 绑定: 与 Element Model Indexer Style RelativeSource 绑定, 以及绑定中的数据转换

作者:webabcd

介绍
重新想象 Windows 8 Store Apps 之 绑定

  • 与 Element 绑定
  • 与 Model 绑定
  • 与 Indexer 绑定
  • 对 Style 中的 Setter 进行绑定(绑定静态资源)
  • Binding 的一个扩展标记 RelativeSource 的应用
  • 绑定中的数据转换

示例
1、演示如何与 Element 绑定,以及 OneTime, OneWay, TwoWay 的区别
Binding/BindingElement.xaml

  1. <Page
  2. x:Class="XamlDemo.Binding.BindingElement"
  3. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  4. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  5. xmlns:local="using:XamlDemo.Binding"
  6. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  7. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  8. mc:Ignorable="d">
  9.  
  10. <Grid Background="Transparent">
  11. <StackPanel Margin="120 0 0 0">
  12.  
  13. <!--
  14. 本例用于演示如何与 Element 绑定,以及 OneTime, OneWay, TwoWay 的区别
  15. -->
  16.  
  17. <!--
  18. OneTime 方式绑定元素
  19. -->
  20. <Slider Name="sliderOneTime" Minimum="1" Maximum="100" Value="10" Width="180" HorizontalAlignment="Left" />
  21. <TextBox Text="{Binding ElementName=sliderOneTime, Path=Value, Mode=OneTime}" Width="150" HorizontalAlignment="Left" />
  22.  
  23. <!--
  24. OneWay 方式绑定元素(OneWay 是默认方式)
  25. -->
  26. <Slider Name="sliderOneWay" Minimum="1" Maximum="100" Value="10" Width="180" HorizontalAlignment="Left" Margin="0 50 0 0" />
  27. <TextBox Text="{Binding ElementName=sliderOneWay, Path=Value, Mode=OneWay}" Width="150" HorizontalAlignment="Left" />
  28.  
  29. <!--
  30. TwoWay 方式绑定元素
  31. -->
  32. <Slider Name="sliderTwoWay" Minimum="1" Maximum="100" Value="10" Width="180" HorizontalAlignment="Left" Margin="0 50 0 0" />
  33. <TextBox Text="{Binding ElementName=sliderTwoWay, Path=Value, Mode=TwoWay}" Width="150" HorizontalAlignment="Left" />
  34.  
  35. </StackPanel>
  36. </Grid>
  37. </Page>

2、演示如何与 Model 进行双向绑定
Binding/BindingModel.xaml

  1. <Page
  2. x:Class="XamlDemo.Binding.BindingModel"
  3. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  4. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  5. xmlns:local="using:XamlDemo.Binding"
  6. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  7. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  8. mc:Ignorable="d">
  9.  
  10. <Grid Background="Transparent">
  11. <StackPanel Margin="120 0 0 0" Name="root">
  12.  
  13. <TextBlock Name="lblMsg" FontSize="14.667" />
  14.  
  15. <TextBox FontSize="14.667" Text="{Binding Path=Name, Mode=TwoWay}" Margin="0 10 10 0" />
  16. <TextBox FontSize="14.667" Text="{Binding Age, Mode=TwoWay}" Margin="0 10 10 0" />
  17. <ToggleSwitch OffContent="女" OnContent="" Header="性别" Margin="0 10 10 0">
  18. <ToggleSwitch.IsOn>
  19. <Binding Path="IsMale" Mode="TwoWay" />
  20. </ToggleSwitch.IsOn>
  21. </ToggleSwitch>
  22.  
  23. </StackPanel>
  24. </Grid>
  25. </Page>

Binding/BindingModel.xaml.cs

  1. /*
  2. * 演示如何与 Model 进行双向绑定
  3. */
  4.  
  5. using System;
  6. using System.ComponentModel;
  7. using Windows.System.Threading;
  8. using Windows.UI.Core;
  9. using Windows.UI.Xaml.Controls;
  10. using XamlDemo.Model;
  11.  
  12. namespace XamlDemo.Binding
  13. {
  14. public sealed partial class BindingModel : Page
  15. {
  16. private Employee _employee;
  17.  
  18. public BindingModel()
  19. {
  20. this.InitializeComponent();
  21.  
  22. this.Loaded += BindingModel_Loaded;
  23. }
  24.  
  25. void BindingModel_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
  26. {
  27. // 创建一个需要绑定的实体对象(注:Employee 实现了 INotifyPropertyChanged 接口,想要 OneWay 或者 TwoWay 的话必须要实现 INotifyPropertyChanged 接口)
  28. _employee = new Employee();
  29. _employee.Name = "webabcd";
  30. _employee.Age = ;
  31. _employee.IsMale = true;
  32.  
  33. // 每 5 秒更新一次数据
  34. ThreadPoolTimer.CreatePeriodicTimer(
  35. (timer) =>
  36. {
  37. var ignored = Dispatcher.RunAsync(CoreDispatcherPriority.High,
  38. () =>
  39. {
  40. Random random = new Random();
  41. _employee.Age = random.Next(, );
  42. _employee.IsMale = random.Next() % == ? true : false;
  43. });
  44. },
  45. TimeSpan.FromMilliseconds());
  46.  
  47. // Employee 对象的属性的值发生变化时触发的事件
  48. _employee.PropertyChanged += _employee_PropertyChanged;
  49.  
  50. root.DataContext = _employee;
  51. }
  52.  
  53. // 每次属性的值发生变化时,显示变化后的结果
  54. void _employee_PropertyChanged(object sender, PropertyChangedEventArgs e)
  55. {
  56. lblMsg.Text = "属性:“" + e.PropertyName + "”的值发生了变化";
  57. lblMsg.Text += Environment.NewLine;
  58. lblMsg.Text += string.Format("当前的值为:Name-{0}, Age-{1}, IsMale-{2}", _employee.Name, _employee.Age, _employee.IsMale);
  59. }
  60. }
  61. }

3、演示如何与索引器进行绑定
Binding/BindingIndexer.xaml

  1. <Page
  2. x:Class="XamlDemo.Binding.BindingIndexer"
  3. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  4. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  5. xmlns:local="using:XamlDemo.Binding"
  6. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  7. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  8. mc:Ignorable="d">
  9.  
  10. <Grid Background="Transparent">
  11. <StackPanel Margin="120 0 0 0">
  12.  
  13. <!--演示如何绑定集合中的某个元素-->
  14. <TextBlock Name="textBlock" FontSize="14.667" Text="{Binding Path=[3] }" />
  15.  
  16. <!--示如何绑定集合中的某个对象的某个属性-->
  17. <TextBlock Name="textBlock2" FontSize="14.667" Text="{Binding Path=[5].Name }" Margin="0 10 0 0" />
  18.  
  19. <!--演示如何绑定 string 类型的索引器-->
  20. <TextBlock Name="textBlock3" FontSize="14.667" Text="{Binding Path=[webabcd] }" Margin="0 10 0 0" />
  21.  
  22. <!--演示如何绑定字典表中指定 key 的数据-->
  23. <TextBlock Name="textBlock4" FontSize="14.667" Text="{Binding Path=[hello] }" Margin="0 10 0 0" />
  24.  
  25. </StackPanel>
  26. </Grid>
  27. </Page>

Binding/BindingIndexer.xaml.cs

  1. /*
  2. * 演示如何与索引器进行绑定
  3. */
  4.  
  5. using System.Collections.Generic;
  6. using Windows.UI.Xaml.Controls;
  7. using XamlDemo.Model;
  8.  
  9. namespace XamlDemo.Binding
  10. {
  11. public sealed partial class BindingIndexer : Page
  12. {
  13. public BindingIndexer()
  14. {
  15. this.InitializeComponent();
  16.  
  17. this.Loaded += BindingIndexer_Loaded;
  18. }
  19.  
  20. void BindingIndexer_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
  21. {
  22. // 用于演示如何绑定集合中的某个元素
  23. List<string> list = new List<string>();
  24. for (int i = ; i < ; i++)
  25. {
  26. list.Add("索引:" + i.ToString());
  27. }
  28. textBlock.DataContext = list;
  29.  
  30. // 用于演示如何绑定集合中的某个对象的某个属性
  31. textBlock2.DataContext = TestData.GetEmployees();
  32.  
  33. // 用于演示如何绑定 string 类型的索引器
  34. textBlock3.DataContext = this;
  35.  
  36. // 用于演示如何绑定字典表中指定 key 的数据
  37. Dictionary<string, string> dic = new Dictionary<string, string>();
  38. dic["hello"] = "hello webabcd";
  39. textBlock4.DataContext = dic;
  40. }
  41.  
  42. // 自定义一个索引器
  43. public object this[string indexer]
  44. {
  45. get
  46. {
  47. return indexer;
  48. }
  49. }
  50. }
  51. }

4、演示 Style 中的 Setter 如何做数据绑定(绑定静态资源)
Binding/BindingStyleSetter.xaml

  1. <Page
  2. x:Class="XamlDemo.Binding.BindingStyleSetter"
  3. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  4. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  5. xmlns:local="using:XamlDemo.Binding"
  6. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  7. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  8. mc:Ignorable="d">
  9.  
  10. <Grid Background="Transparent">
  11. <StackPanel Margin="120 0 0 0">
  12.  
  13. <!--
  14. 演示 Style 中的 Setter 如何做数据绑定
  15. -->
  16.  
  17. <StackPanel.Resources>
  18. <!--设置一些资源-->
  19. <x:Double x:Key="TextFontSize">24.667</x:Double>
  20. <SolidColorBrush x:Key="TextForeground" Color="#00FF00" />
  21.  
  22. <!--为 Style 的 Setter 的 Value 做数据绑定-->
  23. <Style x:Key="MyStyle" TargetType="TextBox">
  24. <Setter Property="FontSize" Value="{Binding Source={StaticResource TextFontSize}}"/>
  25. <Setter Property="Foreground" Value="{Binding Source={StaticResource TextForeground}}"/>
  26. </Style>
  27. </StackPanel.Resources>
  28.  
  29. <!--应用样式-->
  30. <TextBox Text="我是TextBox" Style="{StaticResource MyStyle}" />
  31.  
  32. </StackPanel>
  33. </Grid>
  34. </Page>

5、演示 Binding 中的一个扩展标记 RelativeSource 的应用
Binding/BindingRelativeSource.xaml

  1. <Page
  2. x:Class="XamlDemo.Binding.BindingRelativeSource"
  3. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  4. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  5. xmlns:local="using:XamlDemo.Binding"
  6. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  7. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  8. mc:Ignorable="d">
  9.  
  10. <Grid Background="Transparent">
  11. <StackPanel Margin="120 0 0 0">
  12.  
  13. <!--
  14. 演示 Binding 中的一个扩展标记 RelativeSource 的应用,其用于指定关联数据源为 Self 或 TemplatedParent
  15. 另外简要说明 TemplateBinding 的应用
  16. -->
  17.  
  18. <StackPanel.Resources>
  19. <Style x:Key="MyStyle" TargetType="Button">
  20. <Setter Property="Template">
  21. <Setter.Value>
  22. <ControlTemplate TargetType="Button">
  23. <StackPanel>
  24. <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="White" />
  25. <!--
  26. TemplateBinding 是一个简单版的 Binding,用于在模板中绑定控件的某个属性
  27.  
  28. 如果设计模板时需要用到双向绑定,则 TemplateBinding 就无能为力了(TemplateBinding 是 OneWay 的)
  29. 只能通过 Binding 来做双向绑定,然后通过 RelativeSource={RelativeSource TemplatedParent} 指定数据源来自引用了该 ControlTemplate 的 Control
  30. -->
  31. <Slider Minimum="1" Maximum="100" Width="{TemplateBinding Width}" Value="{Binding Content, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}" />
  32. </StackPanel>
  33. </ControlTemplate>
  34. </Setter.Value>
  35. </Setter>
  36. </Style>
  37. </StackPanel.Resources>
  38.  
  39. <Button Width="300" Content="10" Style="{StaticResource MyStyle}" />
  40.  
  41. <!--
  42. RelativeSource={RelativeSource Self} - 指定数据源为自己本身
  43. -->
  44. <TextBlock Text="{Binding RelativeSource={RelativeSource Self}, Path=Tag}" Tag="webabcd" FontSize="14.667" Margin="0 10 0 0" />
  45.  
  46. </StackPanel>
  47. </Grid>
  48. </Page>

6、演示如何在绑定中做数据转换
Binding/IntegerLetterConverter.cs

  1. /*
  2. * 继承 IValueConverter 以实现一个“整数-字母”转换器
  3. */
  4.  
  5. using System;
  6. using Windows.UI.Xaml.Data;
  7.  
  8. namespace XamlDemo.Binding
  9. {
  10. public sealed class IntegerLetterConverter : IValueConverter
  11. {
  12. /// <summary>
  13. /// 正向转换器。将值从数据源传给绑定目标时,数据绑定引擎会调用此方法
  14. /// </summary>
  15. /// <param name="value">转换之前的值</param>
  16. /// <param name="targetType">转换之后的类型</param>
  17. /// <param name="parameter">转换器所使用的参数(它是通过 Binding 的 ConverterParameter 传递过来的)</param>
  18. /// <param name="language">转换器所使用的区域信息(它是通过 Binding 的 ConverterLanguage 传递过来的)</param>
  19. /// <returns>转换后的值</returns>
  20. public object Convert(object value, Type targetType, object parameter, string language)
  21. {
  22. if ((double)value == )
  23. return "a";
  24. else if ((double)value == )
  25. return "b";
  26. else if ((double)value == )
  27. return "c";
  28. else
  29. return "unknown";
  30. }
  31.  
  32. /// <summary>
  33. /// 反向转换器。将值从绑定目标传给数据源时,数据绑定引擎会调用此方法
  34. /// </summary>
  35. /// <param name="value">转换之前的值</param>
  36. /// <param name="targetType">转换之后的类型</param>
  37. /// <param name="parameter">转换器所使用的参数(它是通过 Binding 的 ConverterParameter 传递过来的)</param>
  38. /// <param name="language">转换器所使用的区域信息(它是通过 Binding 的 ConverterLanguage 传递过来的)</param>
  39. /// <returns>转换后的值</returns>
  40. public object ConvertBack(object value, Type targetType, object parameter, string language)
  41. {
  42. if ((string)value == "a")
  43. return ;
  44. else if ((string)value == "b")
  45. return ;
  46. else if ((string)value == "c")
  47. return ;
  48. else
  49. return ;
  50. }
  51. }
  52. }

Binding/ValueConverter.xaml

  1. <Page
  2. x:Class="XamlDemo.Binding.ValueConverter"
  3. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  4. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  5. xmlns:local="using:XamlDemo.Binding"
  6. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  7. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  8. mc:Ignorable="d">
  9.  
  10. <Grid Background="Transparent">
  11. <StackPanel Margin="120 0 0 0">
  12.  
  13. <!--配置 IValueConverter 资源-->
  14. <StackPanel.Resources>
  15. <local:IntegerLetterConverter x:Key="IntegerLetterConverter"/>
  16. </StackPanel.Resources>
  17.  
  18. <Slider Name="slider" Minimum="1" Maximum="3" Value="1" Width="180" HorizontalAlignment="Left" />
  19. <TextBox Width="150" HorizontalAlignment="Left"
  20. Text="{Binding Value,
  21. Mode=TwoWay,
  22. ElementName=slider,
  23. Converter={StaticResource IntegerLetterConverter},
  24. ConverterParameter=param,
  25. ConverterLanguage=zh_cn}" />
  26.  
  27. <!--注:ConverterParameter 和 ConverterLanguage 不能实现动态的绑定,只能传递静态的参数-->
  28.  
  29. </StackPanel>
  30. </Grid>
  31. </Page>

OK
[源码下载]

重新想象 Windows 8 Store Apps (52) - 绑定: 与 Element Model Indexer Style RelativeSource 绑定, 以及绑定中的数据转换的更多相关文章

  1. 重新想象 Windows 8 Store Apps (15) - 控件 UI: 字体继承, Style, ControlTemplate, SystemResource, VisualState, VisualStateManager

    原文:重新想象 Windows 8 Store Apps (15) - 控件 UI: 字体继承, Style, ControlTemplate, SystemResource, VisualState ...

  2. 重新想象 Windows 8 Store Apps 系列文章索引

    [源码下载][重新想象 Windows 8.1 Store Apps 系列文章] 重新想象 Windows 8 Store Apps 系列文章索引 作者:webabcd 1.重新想象 Windows ...

  3. 重新想象 Windows 8 Store Apps (53) - 绑定: 与 ObservableCollection CollectionViewSource VirtualizedFilesVector VirtualizedItemsVector 绑定

    [源码下载] 重新想象 Windows 8 Store Apps (53) - 绑定: 与 ObservableCollection CollectionViewSource VirtualizedF ...

  4. 重新想象 Windows 8 Store Apps (54) - 绑定: 增量方式加载数据

    [源码下载] 重新想象 Windows 8 Store Apps (54) - 绑定: 增量方式加载数据 作者:webabcd 介绍重新想象 Windows 8 Store Apps 之 绑定 通过实 ...

  5. 重新想象 Windows 8 Store Apps (55) - 绑定: MVVM 模式

    [源码下载] 重新想象 Windows 8 Store Apps (55) - 绑定: MVVM 模式 作者:webabcd 介绍重新想象 Windows 8 Store Apps 之 绑定 通过 M ...

  6. 重新想象 Windows 8 Store Apps (59) - 锁屏

    [源码下载] 重新想象 Windows 8 Store Apps (59) - 锁屏 作者:webabcd 介绍重新想象 Windows 8 Store Apps 之 锁屏 登录锁屏,获取当前程序的锁 ...

  7. 重新想象 Windows 8 Store Apps (16) - 控件基础: 依赖属性, 附加属性, 控件的继承关系, 路由事件和命中测试

    原文:重新想象 Windows 8 Store Apps (16) - 控件基础: 依赖属性, 附加属性, 控件的继承关系, 路由事件和命中测试 [源码下载] 重新想象 Windows 8 Store ...

  8. 重新想象 Windows 8 Store Apps (13) - 控件之 SemanticZoom

    原文:重新想象 Windows 8 Store Apps (13) - 控件之 SemanticZoom [源码下载] 重新想象 Windows 8 Store Apps (13) - 控件之 Sem ...

  9. 重新想象 Windows 8 Store Apps (12) - 控件之 GridView 特性: 拖动项, 项尺寸可变, 分组显示

    原文:重新想象 Windows 8 Store Apps (12) - 控件之 GridView 特性: 拖动项, 项尺寸可变, 分组显示 [源码下载] 重新想象 Windows 8 Store Ap ...

随机推荐

  1. webClient请求JAVA超时解决方案

    private class MyWebClient: WebClient { protected override WebRequest GetWebRequest(Uri uri) { WebReq ...

  2. visual studio 2013使用技巧

    去掉 引用提示 文本编辑器=>所有语言=>codelens visual studio 由于以前的函数求值超时,函数求值被禁用.必须继续执行才能重新启用函数求值 visual studio ...

  3. LintCode-- Remove Linked List Elements

    Remove all elements from a linked list of integers that have valueval. 样例 Given 1->2->3->3- ...

  4. JavaScript - javascript 中的 "||" 与 "&&" 的理解与灵活运

    你肯定见到过这样的代码:a = a||"xxx". 它其实就等价于下面三种形式的代码: a = a || "xxx"; 与: if (!a) { a = &qu ...

  5. nginx 常用配置说明

    一.location 配置 1.1 语法规则: location [=|~|~*|^~] /uri/ { … }= 开头表示精确匹配^~ 开头表示uri以某个常规字符串开头,理解为匹配 url路径即可 ...

  6. 一点一滴之NHibernate

    之前介绍了Dapper,速度很快,很轻量,很好用. 但是Dapper其实有自己的弊端,比如在数据关系复杂,数据库表非常多,多数据库支持,数据库结构变动频繁的时候总是很无奈.尽管有代码生成器,但是代码生 ...

  7. maven中文乱码问题——打包错误

    工程采用GBK编码, web应用中的配置文件打包后,war包里的配置文件里的中文成乱码.   用notepad++打开后,可以看到是用utf-8格式的(可以通过菜单中的[格式]查看),也就是说,在经过 ...

  8. codeforces C. Diverse Permutation(构造)

    题意:1...n 的全排列中 p1, p2, p3....pn中,找到至少有k个 |p1-p2| , |p2-p3|, ...|pn-1 - pn| 互不相同的元素! 思路: 保证相邻的两个数的差值的 ...

  9. Uvaoj 11248 Frequency Hopping(Dinic求最小割)

    题意:1到n节点(节点之间有一定的容量),需要流过C的流量,问是否可以?如果可以输出possible, 否则如果可以扩大任意一条边的容量 可以达到目的,那么输出possible option:接着输出 ...

  10. AEM - Adobe CMS 扒坑记之始

    AEM是Adobe公司所出的商业内容管理系统,全称阿豆比体验管理系统(Adobe Experience Manager),其前身叫CQ,分别有CQ5 CQ6两个大版本.它提供了整套的网站内容管理系统解 ...