【发布时间】:2017-12-09 11:35:32
【问题描述】:
我有一个 IValueConverter,它有一个在 XAML 中设置的 System.Type 属性。
转换器:
internal class EnumTypeConverter : IValueConverter
{
public Type TypeToDisplay { get; set; }
public object Convert(object value, Type targetType, object parameter, string language)
{
return TypeToDisplay?.FullName;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
XAML:
<Page
x:Class="UWPSystemTypeConverterTest.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:converter="using:UWPSystemTypeConverterTest.Converter"
xmlns:enums="using:UWPSystemTypeConverterTest.Enum"
mc:Ignorable="d">
<Page.Resources>
<converter:EnumTypeConverter x:Key="Converter" TypeToDisplay="enums:CustomEnum" />
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<TextBlock Text="{Binding Converter={StaticResource Converter}}" />
</Grid>
</Page>
当我运行应用程序时,我收到以下错误:
Windows.UI.Xaml.Markup.XamlParseException: '与关联的文本 找不到这个错误代码。
创建失败 'UWPSystemTypeConverterTest.Converter.EnumTypeConverter' 来自文本 '枚举:CustomEnum'。 [行:14 位置:56]'
如果我将 CustomEnum 类型的属性添加到从不使用的代码隐藏文件中,则应用程序可以工作。
更改的代码隐藏文件:
public sealed partial class MainPage : Page
{
public CustomEnum WithThisPropertyTheAppWorks { get; set; }
public MainPage()
{
InitializeComponent();
this.DataContext = this;
}
}
完整的复现项目在这里:https://github.com/SabotageAndi/UWPSystemTypeConverterTest
我怀疑 UWP 的优化器导致了这个问题。 真的是这样吗? 如果代码隐藏文件中没有未使用的属性,如何修复错误?
【问题讨论】:
-
我已经运行了您的示例代码并确认了您的发现!不幸的是,这听起来很像 UWP 平台上的错误...
-
您只是想在 TextBlock 中显示 Enum 的 FullName 吗?如果是,请尝试this
-
@AVK:不,这只是该问题的一个小仓库。我们正在通过 Converter 为 ListBox 生成 ItemsSource。我们知道我们可以使用不同的解决方法来实现要求,但我们想知道这里出了什么问题,以防我们将来再次遇到问题。
-
你会考虑
x:Bind吗?这对我来说听起来像是一个错误。 -
我认为最简洁的解决方法是在
App.xaml中定义所有枚举。就像<Application.Resources> <enum:CustomEnum x:Key="Value1">Value1</enum:CustomEnum></Application.Resources>一样,至少您不需要将属性分散到不同的页面中。您也可以尝试向 MSFT 报告。