我做了一个从字符串到颜色和转换的转换器,它在运行时工作正常,但在编辑器上它只是抛出一个"令牌无效。"错误并阻止编辑器显示,真的很烦人,因为它阻止我使用可视化编辑器。
我使用扩展WPF工具包为ColorPicker制作了转换器。
这是转换器代码:
public class MaddoColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Color color = Colors.Black;
if (value != null && !string.IsNullOrWhiteSpace(value.ToString()))
{
string c = value.ToString();
var convertedColor = ColorConverter.ConvertFromString(c);
if (convertedColor != null)
{
color = (Color) convertedColor;
}
}
return color;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null)
{
Color color = (Color)value;
Debug.WriteLine(color.ToString());
return color.ToString();
}
return string.Empty;
}
}
以下是xaml形式的一些相关摘录:
<Window.Resources>
<wpfCatalog:MaddoColorConverter x:Key="ColorConverter" />
</Window.Resources>
<xctk:ColorPicker Grid.Row="3" Grid.Column="2" SelectedColor="{Binding ColoreTestoRGB, Converter={StaticResource ColorConverter}}"/>
答案 0 :(得分:2)
您需要向MaddoColorConverter
添加更多支票。例如,如果绑定失败,WPF会将DependencyProperty.UnsetValue
传递给您的转换器。您的转换器不检查这种情况,而只是转换传递给字符串的任何内容。像这样更改你的转换器(注意我只更新了Convert
方法,没有触及可能需要修复的ConvertBack
,但这与此问题无关):
public class MaddoColorConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
Color color = Colors.Black;
if (value != null && value != DependencyProperty.UnsetValue && value is string && !String.IsNullOrWhiteSpace((string) value)) {
string c = (string) value;
object convertedColor = null;
try {
convertedColor = ColorConverter.ConvertFromString(c);
}
catch (Exception ex) {
throw new FormatException($"String {c} does not represent a valid color", ex);
}
if (convertedColor != null) {
color = (Color) convertedColor;
}
}
return color;
}
}
如果出于某种原因,预计在设计时会出现无效的颜色值 - 请勿在设计时抛出异常,如下所示:
private static readonly DependencyObject _dummy = new DependencyObject();
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
System.Windows.Media.Color color = Colors.Black;
if (value != null && value != DependencyProperty.UnsetValue && value is string && !String.IsNullOrWhiteSpace((string) value)) {
string c = (string) value;
object convertedColor = null;
try {
convertedColor = ColorConverter.ConvertFromString(c);
}
catch (Exception ex) {
if (!DesignerProperties.GetIsInDesignMode(_dummy)) {
throw new FormatException($"String {c} does not represent a valid color", ex);
}
}
if (convertedColor != null) {
color = (Color) convertedColor;
}
}
return color;
}