我正在使用 Xamarin.Forms 和 MvvmCross 编写一个应用程序。我的转换器有问题。在我的
Core
项目中:
public class BoolInverseValueConverter : MvxValueConverter<bool, bool>
{
public bool Convert(bool value, Type targetType, CultureInfo culture, object parameter)
{
return !value;
}
}
在我的
Forms
项目中:
namespace MyApp.Forms.NativeConverters
{
public class BoolInverseValueConverter : MvxNativeValueConverter<MyApp.Core.Converters.BoolInverseValueConverter>
{
}
}
在我的xaml中:
<Application xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:converters="clr-namespace:MyApp.Forms.NativeConverters;assembly=MyApp.Forms"
x:Class="MyApp.Forms.App">
<Application.Resources>
<converters:BoolInverseValueConverter x:Key="BoolInverseValueConverter" />
</Application.Resources>
在我的页面:
<views:MvxContentPage x:TypeArguments="viewModels:LoginViewModel"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:views="clr-namespace:MvvmCross.Forms.Views;assembly=MvvmCross.Forms"
xmlns:mvx="clr-namespace:MvvmCross.Forms.Bindings;assembly=MvvmCross.Forms"
xmlns:viewModels="clr-namespace:MyApp.Core.ViewModels;assembly=MyApp.Core"
xmlns:localviews="clr-namespace:MyApp.Forms.Views;assembly=MyApp.Forms"
xmlns:resx="clr-namespace:MyApp.Core.Resources;assembly=MyApp.Core"
x:Class="MyApp.Forms.Pages.LoginPage"
Title="Login">
<ContentPage.Content>
<localviews:UserLoginView DataContext="{Binding .}" IsVisible="{mvx:MvxBind MyBoolVariable, Converter={StaticResource BoolInverseValueConverter}}"/>
</ContentPage.Content>
</views:MvxContentPage>
当我运行 UWP 应用程序时,我收到消息:
无法分配属性“Converter”:属性不存在或不存在 可分配,或者值和属性之间的类型不匹配
我认为
MvvmCross
没有扫描转换器所在的组件,因此无法找到它。尝试在您的 Setup
: 中注册转换器类程序集
protected override IEnumerable<Assembly> ValueConverterAssemblies
{
get
{
var toReturn = base.ValueConverterAssemblies.ToList();
toReturn.Add(typeof(BoolInverseValueConverter).Assembly);
return toReturn;
}
}
嗨
不知道 MvvmCross,但在你的 xaml 文件中
<Application.Resources>
和
<converters:BoolInverseValueConverter ...>
你添加了吗
<ResourceDictionary>
?
你的转换器应该如下所示
public class BoolInverseValueConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value == null || (value as bool?) == false)
return Visibility.Collapsed;
else
return Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
if (value == null || (value as bool?) == false)
return Visibility.Collapsed;
else
return Visibility.Visible;
}
我最终在没有 MvvmCross 的情况下制作了转换器以使其正常工作。也许这是当前版本的 MvvmCross (6.2.1) 中的一个错误。
对于遇到此错误的其他人来说,还有另一个可能的原因让我困惑了一段时间。
我不小心包含了以下参考(在毛伊岛应用程序中)
using System.Windows.Data;
这意味着无法将 IValueConverter 分配给 Microsoft.Maui.Controls 命名空间中的转换器。
删除 using 语句解决了问题。