WPF中,把TextBox的Text属性绑定到int型的属性上,当一个汉字不能转换的时候,文本框没有通过验证,就会出现红色边框。
如果自定义了一个数据转换器,怎么样定义转换失败的呢?,当然,转换失败的时候,肯定也就没通过验证,而且文本框也会出现红色边框。请问,这个是怎么弄的?
如果自定义了一个数据转换器,怎么样定义转换失败的呢?,当然,转换失败的时候,肯定也就没通过验证,而且文本框也会出现红色边框。请问,这个是怎么弄的?
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (转换成功)
return 转换值;
else
{
return new ValidationResult(false, "错误信息");
}
}
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
Color color;
try
{
color = (Color)value;
return new SolidColorBrush(color);
}
catch {
return new ValidationResult(false, "错误信息");
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(Validation.GetErrors(button1).Count.ToString());
}我这边没有反应呢
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp1"
Title="" Height="400" Width="550" >
<StackPanel>
<StackPanel.Resources>
<local:TestClass x:Key="test" />
<local:ColorConverter x:Key="converter" />
<Style TargetType="TextBox">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors)[0].ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>
</StackPanel.Resources>
<TextBox Text="{Binding Color, Source={StaticResource test}, Converter={StaticResource converter}}" />
<TextBox></TextBox>
</StackPanel>
</Window>using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;namespace WpfApp1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
} class ColorConverter : IValueConverter
{
BrushConverter _converter = new BrushConverter(); public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return _converter.ConvertToString(value as SolidColorBrush); // 这里指从SolidColorBrush转成string
} public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
try
{
return _converter.ConvertFromString(value as string); // 这里指从string转成SolidColorBrush
}
catch
{
return new ValidationResult(false, "错误信息");
}
}
} class TestClass
{
public SolidColorBrush Color { get; set; }
}
}
正规一点的做法是返回 DependencyProperty.UnsetValue