[源码下载]

重新想象 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

<Page
x:Class="XamlDemo.Binding.BindingElement"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:XamlDemo.Binding"
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="120 0 0 0"> <!--
本例用于演示如何与 Element 绑定,以及 OneTime, OneWay, TwoWay 的区别
--> <!--
OneTime 方式绑定元素
-->
<Slider Name="sliderOneTime" Minimum="1" Maximum="100" Value="10" Width="180" HorizontalAlignment="Left" />
<TextBox Text="{Binding ElementName=sliderOneTime, Path=Value, Mode=OneTime}" Width="150" HorizontalAlignment="Left" /> <!--
OneWay 方式绑定元素(OneWay 是默认方式)
-->
<Slider Name="sliderOneWay" Minimum="1" Maximum="100" Value="10" Width="180" HorizontalAlignment="Left" Margin="0 50 0 0" />
<TextBox Text="{Binding ElementName=sliderOneWay, Path=Value, Mode=OneWay}" Width="150" HorizontalAlignment="Left" /> <!--
TwoWay 方式绑定元素
-->
<Slider Name="sliderTwoWay" Minimum="1" Maximum="100" Value="10" Width="180" HorizontalAlignment="Left" Margin="0 50 0 0" />
<TextBox Text="{Binding ElementName=sliderTwoWay, Path=Value, Mode=TwoWay}" Width="150" HorizontalAlignment="Left" /> </StackPanel>
</Grid>
</Page>

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

<Page
x:Class="XamlDemo.Binding.BindingModel"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:XamlDemo.Binding"
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="120 0 0 0" Name="root"> <TextBlock Name="lblMsg" FontSize="14.667" /> <TextBox FontSize="14.667" Text="{Binding Path=Name, Mode=TwoWay}" Margin="0 10 10 0" />
<TextBox FontSize="14.667" Text="{Binding Age, Mode=TwoWay}" Margin="0 10 10 0" />
<ToggleSwitch OffContent="女" OnContent="男" Header="性别" Margin="0 10 10 0">
<ToggleSwitch.IsOn>
<Binding Path="IsMale" Mode="TwoWay" />
</ToggleSwitch.IsOn>
</ToggleSwitch> </StackPanel>
</Grid>
</Page>

Binding/BindingModel.xaml.cs

/*
* 演示如何与 Model 进行双向绑定
*/ using System;
using System.ComponentModel;
using Windows.System.Threading;
using Windows.UI.Core;
using Windows.UI.Xaml.Controls;
using XamlDemo.Model; namespace XamlDemo.Binding
{
public sealed partial class BindingModel : Page
{
private Employee _employee; public BindingModel()
{
this.InitializeComponent(); this.Loaded += BindingModel_Loaded;
} void BindingModel_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
// 创建一个需要绑定的实体对象(注:Employee 实现了 INotifyPropertyChanged 接口,想要 OneWay 或者 TwoWay 的话必须要实现 INotifyPropertyChanged 接口)
_employee = new Employee();
_employee.Name = "webabcd";
_employee.Age = ;
_employee.IsMale = true; // 每 5 秒更新一次数据
ThreadPoolTimer.CreatePeriodicTimer(
(timer) =>
{
var ignored = Dispatcher.RunAsync(CoreDispatcherPriority.High,
() =>
{
Random random = new Random();
_employee.Age = random.Next(, );
_employee.IsMale = random.Next() % == ? true : false;
});
},
TimeSpan.FromMilliseconds()); // Employee 对象的属性的值发生变化时触发的事件
_employee.PropertyChanged += _employee_PropertyChanged; root.DataContext = _employee;
} // 每次属性的值发生变化时,显示变化后的结果
void _employee_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
lblMsg.Text = "属性:“" + e.PropertyName + "”的值发生了变化";
lblMsg.Text += Environment.NewLine;
lblMsg.Text += string.Format("当前的值为:Name-{0}, Age-{1}, IsMale-{2}", _employee.Name, _employee.Age, _employee.IsMale);
}
}
}

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

<Page
x:Class="XamlDemo.Binding.BindingIndexer"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:XamlDemo.Binding"
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="120 0 0 0"> <!--演示如何绑定集合中的某个元素-->
<TextBlock Name="textBlock" FontSize="14.667" Text="{Binding Path=[3] }" /> <!--示如何绑定集合中的某个对象的某个属性-->
<TextBlock Name="textBlock2" FontSize="14.667" Text="{Binding Path=[5].Name }" Margin="0 10 0 0" /> <!--演示如何绑定 string 类型的索引器-->
<TextBlock Name="textBlock3" FontSize="14.667" Text="{Binding Path=[webabcd] }" Margin="0 10 0 0" /> <!--演示如何绑定字典表中指定 key 的数据-->
<TextBlock Name="textBlock4" FontSize="14.667" Text="{Binding Path=[hello] }" Margin="0 10 0 0" /> </StackPanel>
</Grid>
</Page>

Binding/BindingIndexer.xaml.cs

/*
* 演示如何与索引器进行绑定
*/ using System.Collections.Generic;
using Windows.UI.Xaml.Controls;
using XamlDemo.Model; namespace XamlDemo.Binding
{
public sealed partial class BindingIndexer : Page
{
public BindingIndexer()
{
this.InitializeComponent(); this.Loaded += BindingIndexer_Loaded;
} void BindingIndexer_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
// 用于演示如何绑定集合中的某个元素
List<string> list = new List<string>();
for (int i = ; i < ; i++)
{
list.Add("索引:" + i.ToString());
}
textBlock.DataContext = list; // 用于演示如何绑定集合中的某个对象的某个属性
textBlock2.DataContext = TestData.GetEmployees(); // 用于演示如何绑定 string 类型的索引器
textBlock3.DataContext = this; // 用于演示如何绑定字典表中指定 key 的数据
Dictionary<string, string> dic = new Dictionary<string, string>();
dic["hello"] = "hello webabcd";
textBlock4.DataContext = dic;
} // 自定义一个索引器
public object this[string indexer]
{
get
{
return indexer;
}
}
}
}

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

<Page
x:Class="XamlDemo.Binding.BindingStyleSetter"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:XamlDemo.Binding"
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="120 0 0 0"> <!--
演示 Style 中的 Setter 如何做数据绑定
--> <StackPanel.Resources>
<!--设置一些资源-->
<x:Double x:Key="TextFontSize">24.667</x:Double>
<SolidColorBrush x:Key="TextForeground" Color="#00FF00" /> <!--为 Style 的 Setter 的 Value 做数据绑定-->
<Style x:Key="MyStyle" TargetType="TextBox">
<Setter Property="FontSize" Value="{Binding Source={StaticResource TextFontSize}}"/>
<Setter Property="Foreground" Value="{Binding Source={StaticResource TextForeground}}"/>
</Style>
</StackPanel.Resources> <!--应用样式-->
<TextBox Text="我是TextBox" Style="{StaticResource MyStyle}" /> </StackPanel>
</Grid>
</Page>

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

<Page
x:Class="XamlDemo.Binding.BindingRelativeSource"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:XamlDemo.Binding"
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="120 0 0 0"> <!--
演示 Binding 中的一个扩展标记 RelativeSource 的应用,其用于指定关联数据源为 Self 或 TemplatedParent
另外简要说明 TemplateBinding 的应用
--> <StackPanel.Resources>
<Style x:Key="MyStyle" TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<StackPanel>
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="White" />
<!--
TemplateBinding 是一个简单版的 Binding,用于在模板中绑定控件的某个属性 如果设计模板时需要用到双向绑定,则 TemplateBinding 就无能为力了(TemplateBinding 是 OneWay 的)
只能通过 Binding 来做双向绑定,然后通过 RelativeSource={RelativeSource TemplatedParent} 指定数据源来自引用了该 ControlTemplate 的 Control
-->
<Slider Minimum="1" Maximum="100" Width="{TemplateBinding Width}" Value="{Binding Content, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}" />
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</StackPanel.Resources> <Button Width="300" Content="10" Style="{StaticResource MyStyle}" /> <!--
RelativeSource={RelativeSource Self} - 指定数据源为自己本身
-->
<TextBlock Text="{Binding RelativeSource={RelativeSource Self}, Path=Tag}" Tag="webabcd" FontSize="14.667" Margin="0 10 0 0" /> </StackPanel>
</Grid>
</Page>

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

/*
* 继承 IValueConverter 以实现一个“整数-字母”转换器
*/ using System;
using Windows.UI.Xaml.Data; namespace XamlDemo.Binding
{
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 ((double)value == )
return "a";
else if ((double)value == )
return "b";
else if ((double)value == )
return "c";
else
return "unknown";
} /// <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 ((string)value == "a")
return ;
else if ((string)value == "b")
return ;
else if ((string)value == "c")
return ;
else
return ;
}
}
}

Binding/ValueConverter.xaml

<Page
x:Class="XamlDemo.Binding.ValueConverter"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:XamlDemo.Binding"
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="120 0 0 0"> <!--配置 IValueConverter 资源-->
<StackPanel.Resources>
<local:IntegerLetterConverter x:Key="IntegerLetterConverter"/>
</StackPanel.Resources> <Slider Name="slider" Minimum="1" Maximum="3" Value="1" Width="180" HorizontalAlignment="Left" />
<TextBox Width="150" HorizontalAlignment="Left"
Text="{Binding Value,
Mode=TwoWay,
ElementName=slider,
Converter={StaticResource IntegerLetterConverter},
ConverterParameter=param,
ConverterLanguage=zh_cn}" /> <!--注:ConverterParameter 和 ConverterLanguage 不能实现动态的绑定,只能传递静态的参数--> </StackPanel>
</Grid>
</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. 学习之路三十八:Hook(钩子)的学习

    好久没写文章了,还记得年前面试了一家公司,为了检测一下我的学习能力,给了我一个任务,做一个自动登录并自动操作菜单的程序. 花了几天的时间研究了Hook以及使用WindowsAPI操作程序的知识,现在记 ...

  2. PHP高手如何修炼?

    关键字:PHP相关  数据库类 网页相关 服务器相关 数据结构.算法 学习PHP基本功很重要, 最好有数据结构和算法的学习经历. 第一阶段:1-2年新手入门,基础必须完全掌握 smarty+pear+ ...

  3. lua学习项目笔记

    这几天草草的浏览了一下电子版的<lua程序设计>,没有懂的地方就自动忽略了,挑拣了一些可以理解的部分一直在推进.推进至后面的时候已经浑浑噩噩的了,有种想看完这本书的强迫症的感觉.推进CAP ...

  4. 网友对twisted deferr的理解

    事實上Deferred的確就像是一連串的動作,用callback的形式被串在一起,我們用deferred或許可以這樣寫 d.addCallback(洗菜)d.addCallback(切菜)d.addC ...

  5. 许可EDM营销是个长期过程

    为什么这么说呢?基于博主自己这三四年的理解,许可EDM营销确实是个长期的过程,这跟一般的EDM营销有一定的区别. 大多数时候不会有立竿见影的效果,而且需要持续地不间断地进行到底,这也是很多企业实施许可 ...

  6. [转]make: 警告:检测到时钟错误。您的创建可能是不完整的。

    转自http://blog.csdn.net/maopig/article/details/6599660 我在make的时候也出现了同样的问题,不过不是什么大问题,这个不影响编译结果 分析原因可能是 ...

  7. Android系统架构说明介绍

    Android系统架构说明介绍 Android系统架构和一些普遍的操作系统差不多,都是采用了分层的架构,从他们之间的架构图看,Android系统架构分为四个层,从高层到低层分别是应用程序层.应用程序框 ...

  8. 菜鸟学Windows Phone 8开发(4)——设置应用程序样式

    本系列文章来源MSDN的 面向完全新手的 Windows Phone 8 开发  本文地址:http://channel9.msdn.com/Series/Windows-Phone-8-Develo ...

  9. php日期处理 -- 获取本周和上周的开始日期和结束日期(备忘)

    Learn From: http://www.phpernote.com/php-function/1019.html 直接贴代码: <?php header('Content-type: te ...

  10. bootstrap插件学习-bootstrap.tab.js

    先看bootstrap-tab.js的结构 var Tab = function ( element ) {} //构造器 Tab.prototype ={} //构造器的原型 $.fn.tab = ...