近期笔者撸的MVVM项目疯狂使用的数据绑定,而后正好遇到了须要修改绑定源数据的问题了,查询了不少dalao们的答案以及官方文档,发现了解决数据绑定时转换数据的好帮手 -- Convert,下面摘记下关于Convert的简单使用:express
首先,咱们须要了解到咱们什么时候须要使用Convert ?windows
Convert 官网介绍传送门:Converts Classapp
使用Convert的时候咱们首先得新建一个对应咱们使用场景(好比:咱们须要把源数据的日期按咱们指定的格式输出。源数据类型:Data,输出数据类型:String)的XXXConvert 类,而这个类须要实现IValueConverter的接口以及它包含的两个抽象方法:Convert与ConvertBack。ide
上代码:ui
namespace App1 { class TestConvert:IValueConverter { // 当源数据传递过来,在这个方法体内进行修改后而后推到目标位置 public object Convert(object value, Type targetType, object parameter, string language) { Debug.WriteLine("execute Convert method !"); int a = int.Parse(value.ToString()); int b = a * a; return b.ToString(); } // 只有当使用双向绑定的时候,须要将自身的变化推回(push)给源才会调用 public object ConvertBack(object value, Type targetType, object parameter, string language) { Debug.WriteLine("execute ConvertBack method !"); return value; } } }
<Page x:Class="App1.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:App1" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"> <!-- 引入自定义转换器 --> <Page.Resources> <local:TestConvert x:Key="TestConvert"/> </Page.Resources> <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <VisualStateManager.VisualStateGroups> <VisualStateGroup> <VisualState> <VisualState.StateTriggers> <AdaptiveTrigger MinWindowWidth="400"/> </VisualState.StateTriggers> <VisualState.Setters> <Setter Target="test123.Text" Value="1"/> </VisualState.Setters> </VisualState> <VisualState> <VisualState.StateTriggers> <AdaptiveTrigger MinWindowWidth="800"/> </VisualState.StateTriggers> <VisualState.Setters> <Setter Target="test123.Text" Value="2"/> </VisualState.Setters> </VisualState> <VisualState> <VisualState.StateTriggers> <AdaptiveTrigger MinWindowWidth="1000"/> </VisualState.StateTriggers> <VisualState.Setters> <Setter Target="test123.Text" Value="3"/> </VisualState.Setters> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <Grid.RowDefinitions> <RowDefinition Height="15*"/> <RowDefinition Height="2*"/> </Grid.RowDefinitions> <Pivot SelectedIndex="0" Grid.Row="0"> <PivotItem Header="Test Header 1"> <TextBlock x:Name="test123" Text="Pivot Item 1"/> </PivotItem> <PivotItem Header="Test Header 2"> <TextBlock Text="{x:Bind test123.Text,Converter={StaticResource TestConvert},Mode=OneWay}"/> </PivotItem> </Pivot> </Grid> </Page>
为了方便理解,先谈下{x:Bind}以及Binding的区别,这里引用一段官方陈述:spa
The binding objects created by** {x:Bind}** and {Binding} are largely functionally equivalent. But **{x:Bind}**executes special-purpose code, which it generates at compile-time, and {Binding} uses general-purpose runtime object inspection. Consequently, **{x:Bind} **bindings (often referred-to as compiled bindings) have great performance, provide compile-time validation of your binding expressions, and support debugging by enabling you to set breakpoints in the code files that are generated as the partial class for your page. These files can be found in your obj folder, with names like (for C#) <view name>.g.cs 摘自:{x:bind} markup extensiondebug
OK,简单复述下上面那段话的意思:{x:Bind}绑定数据的时候,会在编译期间生成一段用于检索绑定数据的目标代码,而且执行,而Binding是直接在运行时进行对象检查。双向绑定
 而后就是回到Convert的简述中,简单介绍下两个待实现的抽象方法:Convert和ConvertBack,通常状况下若是咱们只须要将源数据进行加工直接推送到目标位置的话,Convert便足够了(通常若是绑定的模式选择的是:OneWay 单向绑定,只会调用Convert方法)。假若使用场景要求不只得将处理数据推送到目标位置,还得将修改后数据推送回源数据位置,那么实现上述回调功能的代码就应该放在ConvertBack方法内。code
补充:关于{x:Bind}以及Binding容易忽略的默认模式,引用官方陈述👇orm
{x:Bind} has a default mode of OneTime, unlike {Binding}, which has a default mode of OneWay. This was chosen for performance reasons, as using OneWay causes more code to be generated to hookup and handle change detection. You can explicitly specify a mode to use OneWay or TwoWay binding. You can also use x:DefaultBindMode to change the default mode for {x:Bind} for a specific segment of the markup tree. The specified mode applies to any {x:Bind} expressions on that element and its children, that do not explicitly specify a mode as part of the binding
补充:关于{x:Bind}的简单使用示例->
Text="{x:Bind MyModel.Order.CalculateShipping(MyModel.Order.Weight, MyModel.Order.ShipAddr.Zip, 'Contoso'), Mode=OneTime}" | Path to function | Path argument | Path argument | Const arg | Bind Props
补充:双向绑定回调:
Two way function bindings In a two-way binding scenario, a second function must be specified for the reverse direction of the binding. This is done using the BindBack binding property, for example Text="{x:Bind a.MyFunc(b), BindBack=a.MyFunc2}". The function should take one argument which is the value that needs to be pushed back to the model.
PS:
OK,就先介绍到这!