使用 XAML/C 将内容添加到列表框项目#

Add content to Listbox Items using XAML/C#

我刚开始使用 VS2017 和 C# 并为 Windows 10 IoT 设备 (RPi) 创建应用程序。所以我在一个空白的应用程序中使用 C# 和 XAML 来设计一个 GUI。

我已经在 XAML 中完成了界面的完整设计,现在我正在尝试将数据填充到界面中并创造魔力让想法发挥作用 ;)。

部分XAML代码:

<StackPanel x:Name="DetailHome" Grid.Column="1" Visibility="Visible">
        <ListBox x:Name="ParaBox" HorizontalAlignment="Left" Height="193" Margin="20,147,0,-340" VerticalAlignment="Top" Width="380" IsSynchronizedWithCurrentItem="False">
            <ListBoxItem x:Name="Parameter01" Content="Acceleration (mm/s²)"/>
            <ListBoxItem x:Name="Parameter02" Content=""/>
            <ListBoxItem x:Name="Parameter03" Content=""/>
            <ListBoxItem x:Name="Parameter04" Content=""/>
            <ListBoxItem x:Name="Parameter05" Content=""/>
            <ListBoxItem x:Name="Parameter06" Content=""/>
            <ListBoxItem x:Name="Parameter07" Content=""/>
            <ListBoxItem x:Name="Parameter08" Content=""/>
            <ListBoxItem x:Name="Parameter09" Content=""/>
            <ListBoxItem x:Name="Parameter10" Content=""/>
        </ListBox>
        <TextBox x:Name="txtBoxValue" HorizontalAlignment="Left" Margin="40,105,0,-140" Text="Value" VerticalAlignment="Center" Height="35" Width="345"/>
        <Button x:Name="BtnApply" Content="Apply" HorizontalAlignment="Left" Margin="20,60,0,-100" VerticalAlignment="Top" Height="40" Width="380"/>
        <TextBlock x:Name="lblSpeedValue" HorizontalAlignment="Center" Margin="287,354,37,-393" Text="Speed Value" Height="25" Width="100" VerticalAlignment="Center"/>
        <TextBlock x:Name="lblSpeed" HorizontalAlignment="Left" Margin="50,363,0,-393" Text="Calculated speed:" TextWrapping="WrapWholeWords" Height="30" Width="120" TextAlignment="Center" LineStackingStrategy="MaxHeight" OpticalMarginAlignment="None" IsDoubleTapEnabled="False" IsHoldingEnabled="False" IsRightTapEnabled="False" IsTapEnabled="False" TextReadingOrder="Default" TextTrimming="None"/>
    </StackPanel>

ListBoxItems 的内容不固定。它可以改变,所以我需要使用 c# 文件填充内容。在上面的 XAML 代码中,只有一个 Item 已经填充了例如文本 "Acceleration (mm/s²)" 作为内容。 因为 ListBoxItems 已命名,所以我尝试使用以下 C# 代码:

Parameter01.content = Parameters[0].Name;

Parameters[n]是一个数组,里面存放着我要显示的参数的数据。但这不起作用,Parameter01 未被识别为我之前在 XAML 代码中定义的 ListBoxItem。

如何帮我解决这个问题?

您应该使用 ParaBox.ItemsSource = 参数,并使用 DisplayMemberPath 获取每个列表框项目中的 Name 对象,而不是定义 XAML 中的项目,让它们动态填充

Parabox.ItemsSource = Parameters;
Parabox.DisplayMemberPath = nameof(yourType.Name);

这还允许您添加或删除参数而无需更改 xaml,只需在参数列表中添加或删除即可。

与此同时,我发现我没有使用正确的方法来访问 XAML-对象!

将我的代码移动到另一个方法(通过特定操作运行,如按下按钮)有效。