Bindingする値を変換する
BindingConveterの基本的な話です。
ModelとUIとのバインドにはIValueConveterというクラスを使うことでバインドする値を変換することが可能です。
まずはIValueConveterを実装した変換クラスを作成
public class IntegerToStringConverter:IValueConverter { //Model→UI public object Convert(object value, Type targetType, object parameter, string language) { var v = value.ToString(); return int.Parse(v); } //UI→Model public object ConvertBack(object value, Type targetType, object parameter, string language) { return value.ToString(); } }
Convertでバインド先(Model)からバインド元(UI)へ
ConvertBackでバインド元(UI)からバインド先(Model)への変換を行います。
あとはテキトーなモデルをつくって
public class Model:INotifyPropertyChanged { public Model() { } private int integerText; public int IntegerText { get { return integerText; } set { integerText = value; PropertyChanged(this,new PropertyChangedEventArgs("IntegerText")); } } public event PropertyChangedEventHandler PropertyChanged; }
UIはこんなかんじ。BindingのConveterのところにリソースにいれたConveterをいれる
<Page x:Class="App6.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:App6" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"> <Page.DataContext> <local:Model /> </Page.DataContext> <Page.Resources> <local:IntegerToStringConverter x:Key="converter" /> </Page.Resources> <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <TextBox Text="{Binding IntegerText,Converter={StaticResource converter},Mode=TwoWay}" Width="200" Height="80" Margin="405,314,761,374"/> <Button Content="Button" HorizontalAlignment="Left" Margin="746,384,0,0" VerticalAlignment="Top" Click="Button_Click"/> </Grid> </Page>