2011-05-08 59 views
1

我定義了一些ItemsControl並將其添加到ItemsControl.Items中一個12個RadioButtons。 其中一個RadioButton被選中。 我想找到Checked RadioButton的上下文。如何使用Linq在ItemsControl.Items中找到正確的項目

,我寫的(而不能很好地工作)的代碼

string str = (from t1 in itemsControl.Items.OfType<RadioButton>() 
       where t1.IsChecked == true 
       select t1.Content).ToString(); 

什麼是我的錯? 我如何以其他方式做到這一點(我不想用於/ foreach循環)

謝謝。

回答

2

你的結果是目前的IEnumerable<object>有一個元素(一個內容檢查單選按鈕) - 但你只需要這一個元素本身,你可以使用Single()

string str = (from t1 in itemsControl.Items.OfType<RadioButton>() 
       where t1.IsChecked 
       select t1.Content).Single().ToString(); 

而且t1.IsChecked已經是布爾型的,不需要與true進行比較。

相關問題