首页 文章

使用XAML / C#向Listbox项添加内容#

提问于
浏览
0

我刚开始使用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代码中,只有一个项目已经填充,例如文本“加速度(mm /s²)”作为内容 . 因为ListBoxItems是命名的,所以我尝试以下C#代码:

Parameter01.content = Parameters[0].Name;

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

怎么能帮我清除这个?

2 回答

  • 0

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

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

    这也允许您添加或删除参数,而无需更改您的xaml,只需在参数列表中添加或删除 .

  • 1

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

    将我的代码移动到另一个方法(由按下按钮之类的特定操作运行)可以正常工作 .

相关问题