[英]ComboBox crashing with custom ItemTemplate
我正在编写一个 WinUI 3 应用程序并制作一个对话框,用户可以在其中 select 多种 object 类型之一。
对于 ComboBox 的 ItemTemplate,我使用了 TextBlock,其 Text 绑定到 Name 属性(以显示类型的名称)。
但是,如果我将 ItemsSource 设置为 Type 数组,则应用程序会在打开 ComboBox 的下拉菜单时崩溃,但类型为 Microsoft.Ui.Xaml.UnhandledException。 通过代码设置 SelectedIndex 属性具有相同的效果。
调试时,应用程序会在编译器生成的名为 App.gics 的文件中的以下方法的最后一个 if 语句处中断。
public void InitializeComponent()
{
if (_contentLoaded)
return;
_contentLoaded = true;
global::System.Uri resourceLocator = new global::System.Uri("ms-appx:///App.xaml");
global::Microsoft.UI.Xaml.Application.LoadComponent(this, resourceLocator);
#if DEBUG && !DISABLE_XAML_GENERATED_BINDING_DEBUG_OUTPUT
DebugSettings.BindingFailed += (sender, args) =>
{
global::System.Diagnostics.Debug.WriteLine(args.Message);
};
#endif
#if DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION
UnhandledException += (sender, e) =>
{
if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();
};
#endif
}
这页纸:
<Page
x:Class="RayMarchEditor.ChooseObjectTypePage"
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"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<ComboBox x:Name="comboBox" HorizontalAlignment="Stretch">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name, Mode=OneTime}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</Page>
代码隐藏:
using Microsoft.UI.Xaml.Controls;
using System;
namespace RayMarchEditor
{
public sealed partial class ChooseObjectTypePage : Page
{
public ChooseObjectTypePage()
{
this.InitializeComponent();
comboBox.ItemsSource = new Type[] { typeof(string) };
}
}
}
我必须重现您的错误,但无法理解原因。 Type
是抽象的 class 但这不应该是问题。 也许这是WinUI 3的问题。
无论如何,您需要用视图 model class 或其他东西来包装它,它应该可以工作。
类型视图模型.cs
public class TypeViewModel
{
public Type Type { get; }
public TypeViewModel(Type type)
{
Type = type;
}
}
选择ObjectTypePage.xaml.cs
public sealed partial class ChooseObjectTypePage : Page
{
public ChooseObjectTypePage()
{
this.InitializeComponent();
comboBox.ItemsSource = new TypeViewModel[] { new TypeViewModel(typeof(string)) };
}
}
选择ObjectTypePage.xaml
<ComboBox x:Name="comboBox" HorizontalAlignment="Stretch">
<ComboBox.ItemTemplate>
<DataTemplate x:DataType="local:TypeViewModel">
<TextBlock Text="{Binding Type.Name}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.