簡體   English   中英

使用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代碼中,僅已經填充了一個項目,例如以文本“ Acceleration(mm /s²)”作為內容。 因為ListBoxItems是命名的,所以我嘗試以下C#代碼:

Parameter01.content = Parameters[0].Name;

Parameters[n]是一個數組,其中包含我要顯示的參數的數據。 但這不起作用,無法將Parameter01識別為我之前在XAML代碼中定義的ListBoxItem。

如何幫助我解決這個問題?

您應該使用ParaBox.ItemsSource = Parameters,並使用DisplayMemberPath來獲取每個列表框項目中的Name對象,而不是在XAML中定義項目,而是讓它們動態填充

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

這還允許您添加或刪除參數而不必更改xaml,只需從“參數”列表中添加或刪除即可。

同時,我發現我不希望使用正確的方法來訪問XAML對象!

將我的代碼移動到另一種方法(通過某種操作(如按下按鈕)運行)即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM