[英]wpf converter “token is not valid” in editor, ColorPicker from extended WPF toolkit
我做了一个从字符串到颜色再到颜色的转换器,它在运行时工作正常,但是在编辑器上它只抛出“令牌无效”。 错误并阻止编辑器显示,这确实很烦人,因为它阻止了我使用可视编辑器。
我使用扩展的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}}"/>
您需要向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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.