我有一个MVVM WPF应用程序。我有下面的转换器:
public class PrintIconVisibilityValueConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values[0] == null || values[1] == null) return Visibility.Collapsed;
int item1 = (int)values[0];
string item2 = (string)values[1];
if (item1 > 0 || !string.IsNullOrEmpty(item2))
{
return Visibility.Visible;
}
else
{
return Visibility.Collapsed;
}
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
我认为:
<Window.Resources>
<classes:PrintIconVisibilityValueConverter x:Key="PrintIconVisibilityValueConverter"/>
</Window.Resources>
然后我在此 View 中有一个图像:
<Image Source="/MyImages;component/Images/PrintIco.png"
Height="15" Margin="20 0 5 0">
<Image.Visibility>
<MultiBinding Converter="{StaticResource PrintIconVisibilityValueConverter}">
<Binding Path="Item1" />
<Binding Path="Item2" />
</MultiBinding>
</Image.Visibility>
</Image>
Item1和Item2是 View 模型中的公共(public)属性:
private string _item2 = string.Empty;
public string Item2
{
get
{
return _item2;
}
set
{
if (_item2 == value) return;
_item2 = value;
OnPropertyChanged("Item2");
}
}
private int _item1;
public int Item1
{
get
{
return _item1;
}
set
{
if (_item1 == value) return;
_item1 = value;
OnPropertyChanged("Item1");
}
}
它可以正确编译,并且我可以毫无问题地执行该应用程序,但是在设计时,该 View 没有显示,错误提示“不受控制的异常”并指向该行:
int item1 = (int)values[0];
在PrintIconVisibilityValueConverter类中。
在 View 中显示的异常的屏幕截图下方:
最佳答案
一些建议;
在转换器中调用GetIsInDesignMode
方法,如果返回true
,则立即返回:
public class PrintIconVisibilityValueConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))
return Visibility.Visible;
...
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
在XAML中设置
DataContext
:<Window.DataContext>
<local:ViewModel />
</Window.DataContext>
设置设计时间数据上下文:
<Window ... d:DataContext ="{d:DesignInstance {x:Type local:ViewModel}, IsDesignTimeCreatable=True}">
或Disable XAML UI designer
关于c# - WPF XAML : The specified conversion is not valid中的不受控制的异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51308281/