簡體   English   中英

從xaml設計轉換為C#編碼

[英]Changing from xaml design into C# coding

我目前正嘗試以編程方式獲取ListBox,我試圖找到很多方法但是,我不能使這個工作。

這是代碼的xaml部分:

<ListBox Grid.Row="2" Grid.ColumnSpan="2" x:Name="PeerList" Margin="10,10,0,10">
    <ListBox.ItemTemplate>
         <DataTemplate>
              <TextBlock Text="{Binding DisplayName}" FontSize="{StaticResource PhoneFontSizeMedium}" Margin="40,0,0,0"/>
         </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

我希望以編程方式完成相同的操作。

XAML對C#熟悉的人幫我解決了這個問題。

在此輸入圖像描述

就是這樣的

ListBox listbox = new ListBox();
DataTemplate dataTemplate = new DataTemplate();
FrameworkElementFactory elementFactory = new FrameworkElementFactory(typeof(TextBlock));
elementFactory .SetBinding(TextBlock.TextProperty, new Binding("DisplayName"));
dataTemplate.VisualTree = elementFactory;

listbox.ItemTemplate = dataTemplate ;

如果您希望以編程方式顯示此列表中對等項的名稱,請關注@HiệpLê答案。

否則,如果您只想獲得同行的名稱。 按照這個。

void SearchPeers()
 {
     List<string> name = new List<string>();
     var peers = await PeerFinder.FindAllPeersAsync();
     for(int i=0;i<peers.Count;i++)
     {
       string peerName = peers.DisplayName;
       name.Add(peerName);
     }
 }

這將為您提供可用的同行的名稱。

暫無
暫無

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

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