首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

WPF,请教自定义的验证规则和转换器

2013-08-16 
WPF,请问自定义的验证规则和转换器WPF中,把TextBox的Text属性绑定到int型的属性上,当一个汉字不能转换的时

WPF,请问自定义的验证规则和转换器
WPF中,把TextBox的Text属性绑定到int型的属性上,当一个汉字不能转换的时候,文本框没有通过验证,就会出现红色边框。


如果自定义了一个数据转换器,怎么样定义转换失败的呢?,当然,转换失败的时候,肯定也就没通过验证,而且文本框也会出现红色边框。请问,这个是怎么弄的?
[解决办法]
在转换类中:
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (转换成功)
return 转换值;
else
{
return new ValidationResult(false, "错误信息");
}
}

[解决办法]
http://msdn.microsoft.com/zh-cn/library/vstudio/ms752347.aspx
[解决办法]
嗯,我看了转换的时候没有办法报告自定义的出错信息,只能得到“xxx无法转换”这样的笼统提示信息。

要报告自定的提示信息,还是要把检查放到set property的时候,或者些自定义的ValidationRule
[解决办法]
你的完整程序怎么样的?看下这个例子,出错时会有tooltip提示:


<Window x:Class="WpfApp1.MainWindow"
    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; }
}

}

[解决办法]
其实这是我的误解,返回任何不能转成SolidColorBrush(绑定源类型)的东西都会让wpf报xxx无法转换。
正规一点的做法是返回 DependencyProperty.UnsetValue
[解决办法]
wpf对这个值有特殊判断,如果返回它就直接认为转换失败,否则会去判断一下返回值是否可以转成目标值,不能就认为转换失败。

热点排行