2013-10-25 47 views
1

我目前試圖以編程方式獲取列表框 我試圖找到很多方法,但是我無法做到這一點。從xaml設計改爲C#編碼

這裏是代碼的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#可以幫助我解決這個問題。 。

enter image description here

回答

1

如果你想以編程方式顯示在此列表中的同齡人的名字的意思是關注@協Lê答案。

否則,如果你只想得到同齡人的名字。按照這個。

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); 
    } 
} 

這會得到你可用的同伴的名字。

2

它是這樣的

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 ; 
+0

我無法在我的Visual Studio 2012 for Windows Phone8中使用FrameWorkElementFactory。該特殊功能僅適用於最終版本嗎? – Ethan

+0

FrameWorkElementFactory是在.NET 3.0中引入的,適用於所有版本的Visual Studio。 – Stewbob

+0

@Stewbob我目前正在使用Visual Studio 2012速成版。我嘗試輸入FrameworkElementFactory。但它沒有在我的編輯器中顯示該選項。這個scnario的圖像在上面的問題中編輯 – Ethan