Chciałbym przedłużyć to, co już zareagowała Rachel. Jeśli numer telefonu jest liczbą całkowitą, StringFormat będzie działał dobrze. Jeśli numer telefonu jest ciągiem, przekonałem się, że Konwerter jest całkiem przydatny. Dzięki temu nie trzeba tworzyć dodatkowej właściwości dla klasy.
Oto przykład:
public class StringToPhoneConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return string.Empty;
//retrieve only numbers in case we are dealing with already formatted phone no
string phoneNo = value.ToString().Replace("(", string.Empty).Replace(")", string.Empty).Replace(" ", string.Empty).Replace("-", string.Empty);
switch (phoneNo.Length)
{
case 7:
return Regex.Replace(phoneNo, @"(\d{3})(\d{4})", "$1-$2");
case 10:
return Regex.Replace(phoneNo, @"(\d{3})(\d{3})(\d{4})", "($1) $2-$3");
case 11:
return Regex.Replace(phoneNo, @"(\d{1})(\d{3})(\d{3})(\d{4})", "$1-$2-$3-$4");
default:
return phoneNo;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
}
XAML:
<TextBox Text="{Binding SelectedParticipant.PhoneNumber, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource StringToPhoneConverter}}" />
Dlaczego nie umieścić to bezpośrednio do modelu i dodać ToFormattedString() lub innej własności którym wiązania? Możesz także użyć konwertera. –