代码之家  ›  专栏  ›  技术社区  ›  Scott Vercuski

WPF文本框中的执行顺序

  •  1
  • Scott Vercuski  · 技术社区  · 14 年前

    我遇到了一个格式化转换器和数据验证的问题。我有下面的textbox XAML声明

    <TextBox FontFamily="Segoe" FontSize="16" FontWeight="Medium"
        TabIndex="{Binding TabBinding}"  Foreground="Black"
        Opacity="0.9" IsTabStop="True" Uid="{Binding PriceID}"
        Text="{Binding NewPrice,Converter={StaticResource FormattingConverter},
        ConverterParameter=' \{0:C\}', Mode=TwoWay, UpdateSourceTrigger=LostFocus}"
        Background="#FFE6DED3" BorderBrush="#FFE6DED3"
        DataContext="{Binding StringFormat=\{0:c\}, NotifyOnValidationError=True}"
        Padding="0" KeyDown="TextBox_KeyDown" AcceptsReturn="False">
    </TextBox>
    

    public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    {
        var objTypeConverter = System.ComponentModel.TypeDescriptor.GetConverter(targetType);
        object objReturnValue = null;
    
        if (objTypeConverter.CanConvertFrom(value.GetType())) {
            objReturnValue = objTypeConverter.ConvertFrom(value.ToString().Replace("$", ""));
        }
    
        return objReturnValue;
    }
    

    谢谢您,

    1 回复  |  直到 14 年前
        1
  •  0
  •   Adam Sills    14 年前

    转换器的ConvertBack总是将数据转换为适合目标对象的值。转换器负责处理异常(在异常的情况下,返回原始值,这样绑定框架也会意识到它是无效值)。

    public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)  
    { 
        var objTypeConverter = System.ComponentModel.TypeDescriptor.GetConverter(targetType); 
        // Default return value is the original value - if conversion fails, return
        // this value so the binding framework will see an invalid value (and not 
        // just null).
        object objReturnValue = value; 
    
        if (objTypeConverter.CanConvertFrom(value.GetType())) { 
            try {
                objReturnValue = objTypeConverter.ConvertFrom(value.ToString().Replace("$", "")); 
            }
            catch( FormatException ) { }
            // Catch all of your possible exceptions and ignore them by returning the original value
        } 
    
        return objReturnValue; 
    }