1、定義轉換類3d
public class IdNoConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { string no = value?.ToString() ?? ""; if (no.Length > 14) return no.Substring(0, 6) + " " + no.Substring(6, 8) + " " + no.Substring(14); else if (no.Length > 6) return no.Substring(0, 6) + " " + no.Substring(6); return no; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return (value?.ToString() ?? "").Replace(" ", ""); } } public class MobileConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { string no = value?.ToString() ?? ""; if (no.Length > 7) return no.Substring(0, 3) + " " + no.Substring(3, 4) + " " + no.Substring(7); else if (no.Length > 3) return no.Substring(0, 3) + " " + no.Substring(3); return no; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return (value?.ToString() ?? "").Replace(" ", ""); } }
2、添加到資源code
<local:IdNoConverter x:Key="IC"/> <local:MobileConverter x:Key="MC"/>
3、文本框設置blog
<TextBox Text="{Binding IdNo,Converter={StaticResource IC},UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top"></TextBox> <TextBox Text="{Binding Mobile,Converter={StaticResource MC},UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Margin="0,20"></TextBox>
4、結果
資源