在c# WPF列表框中添加XAML自定义类
本文关键字:添加 XAML 自定义 WPF 列表 | 更新日期: 2023-09-27 18:17:10
我有一个类PC
,其中包含Image
, Label
(与XAML
设计),我想在其他类中获得ListBox
中的pc列表。
我试过了,但我得到错误System.Windows.Markup.XamlParseException
:
pc p = new pc();
list_pc.Items.Add(p);
(where list_pc is a ListBox)
这是单个PC
的XAML
:
<Window
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"
x:Class="TnCyberCafe.pc"
Title="pc"
SizeToContent="WidthAndHeight"
ShowInTaskbar="False"
WindowStartupLocation="CenterScreen"
WindowStyle="None"
AllowsTransparency="True"
Background="Transparent" Width="95" Height="104.982">
<Grid HorizontalAlignment="Left" Margin="0,10,-15,10" Width="110">
<Image x:Name="image" HorizontalAlignment="Left" Height="96" VerticalAlignment="Top" Width="100" Source="Resources/aaa.png" RenderTransformOrigin="0.5,0.26" Margin="0,-16,0,0"/>
<Label Content="Label" HorizontalAlignment="Left" Height="25" Margin="20,70,0,-10" VerticalAlignment="Top" Width="45"/>
</Grid>
</Window>
这是list_pc
的XAML
:
<ListBox x:Name="liste_pc" ScrollViewer.VerticalScrollBarVisibility="Disabled">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True" Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
List PCs
</ListBox>
您关于System.Windows.Markup.XamlParseException的第一个问题:
正如Garry Vass提到的,有些地方出了问题,但没有告诉你到底发生了什么。如果您在Visual Studio中开发,请单击Debug选项卡下的Exceptions并启用Common Language Runtime Exceptions。这将指向错误代码。
对于第二个问题,您应该有如下所示的数据绑定和ListBox Itemtemplate
<ListBox x:Name="liste_pc" ItemsSource="{Binding PCList}" ScrollViewer.VerticalScrollBarVisibility="Disabled">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding PCImageSource}" />
<Label Content="{Binding Path=PCName}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
其中PCList是PC类对象项的可观察集合