使用 XAML/C# 向列表框项添加内容

Posted

技术标签:

【中文标题】使用 XAML/C# 向列表框项添加内容【英文标题】:Add content to Listbox Items using XAML/C# 【发布时间】:2018-06-18 16:16:54 【问题描述】:

我刚开始使用 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#-file 填充内容。在上面的 XAML 代码中,只有一个 Item 已经填充了例如文本“Acceleration (mm/s²)”作为内容。 因为 ListBoxItems 是命名的,所以我尝试使用以下 C# 代码:

Parameter01.content = Parameters[0].Name;

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

如何帮助我解决这个问题?

【问题讨论】:

它是否适用于 Parameter01.Content(大写 C)? @Oystein 不,也不起作用。 【参考方案1】:

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

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

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

【讨论】:

【参考方案2】:

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

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

【讨论】:

以上是关于使用 XAML/C# 向列表框项添加内容的主要内容,如果未能解决你的问题,请参考以下文章

从运行时添加的列表框项中获取字符串[重复]

如何通过Powershell代码更改特定WPF列表框项的背景颜色?

将列表框项添加到 SQL Server 列作为列名

仅根据所选的列表框项加载DataGridView一次

如何使用 wpf 代码隐藏在列表框中隐藏单个列表框项?

从列表框项中获取文本