2011-02-11 20 views
0

請檢查ListBox中的代碼,我使用怎樣訪問一個單選按鈕一ListBoxItem的內部,Windows Phone 7的

<ListBox Name="listBoxDefaultAcc" HorizontalAlignment="Left" VerticalAlignment="Top" Width="450" Height="410"> 
       <ListBox.ItemTemplate> 
        <DataTemplate> 
         <StackPanel Orientation="Horizontal" Height="60" Width="450"> 
          <RadioButton Content="{Binding}" GroupName="defaultAcc" HorizontalAlignment="Left" VerticalAlignment="Center" Height="80" Width="450" /> 
         </StackPanel> 
        </DataTemplate> 
       </ListBox.ItemTemplate> 
      </ListBox> 

現在我想從代碼隱藏訪問RadioButtoncontent財產。

ListBoxItems都可以從代碼隱藏動態充滿了下面的代碼:

listBoxDefaultAcc.ItemsSource = from acc in db.Table<Accounts>() 
             select acc.accName; 

請幫我出這一點。

+0

當你想訪問該和哪個`RadioButton`?一個側面說明,我不認爲'ListBoxItem` s爲選擇與ItemTemplate中 – 2011-02-11 08:26:22

+0

我想借此選擇`RadioButton`的內容,並將其存儲在獨立存儲,如果這個'ItemTemplate`不會再幫你能否建議我以正確的方式來做到這一點。下面是使用上面的代碼生成的GUI屏幕截圖。 [鏈接](http://img824.imageshack.us/i/capturejcf.png) – Piyush 2011-02-11 08:37:44

回答

1

您可以使用VisualTreeHelper並深入控制。不過這不推薦。
更好的是你的DataTemplate只綁定到控件的屬性,然後通過獲取綁定值檢索值。從技術上講,在這種情況下,如果你想改變單選按鈕的內容,那麼你需要更改項目中的項目

你能通過獲取單選按鈕的內容來解釋你想要實現的嗎?

編輯* * ** * ** * **

<ListBox Name="listBoxDefaultAcc" HorizontalAlignment="Left" VerticalAlignment="Top" Width="450" Height="410"> 
       <ListBox.ItemTemplate> 
        <DataTemplate> 
         <StackPanel Orientation="Horizontal" Height="60" Width="450"> 
          <RadioButton Content="{Binding Name}" IsChecked="{Binding Selected, Mode=TwoWay}" GroupName="defaultAcc" HorizontalAlignment="Left" VerticalAlignment="Center" Height="80" Width="450" /> 
         </StackPanel> 
        </DataTemplate> 
       </ListBox.ItemTemplate> 

public partial class Home : Page 
{ 
    public Home() 
    { 
     InitializeComponent(); 
     var items = new List<SomeClass>(); 
     items.Add(new SomeClass() {Name = "a"}); 
     items.Add(new SomeClass() {Name = "b"}); 
     items.Add(new SomeClass() {Name = "c"}); 

     listBoxDefaultAcc.ItemsSource = items; 
    } 

    // Executes when the user navigates to this page. 
    protected override void OnNavigatedTo(NavigationEventArgs e) 
    { 
    } 

    private void testButton_Click(object sender, RoutedEventArgs e) 
    { 
     var items = (List<SomeClass>)listBoxDefaultAcc.ItemsSource; 
     var selectedItem = items.Where(x => x.Selected).FirstOrDefault(); 
    } 

    class SomeClass 
    { 
     public string Name { get; set; } 
     public bool Selected { get; set; } 
    } 
} 
1

您應該使用數據綁定。您應該將內容綁定到表示內容的屬性,您將設置爲項目。

這樣,你不必在意列表框或模板或任何東西。你只是在操縱對象,而這些變化會在GUI中反映出來。