2013-08-19 45 views
0

我有一個Windows Phone 8應用程序中的listPicker,並且想知道我在做錯了什麼來收集當前在c#中選擇的項目。Windows Phone的ListPicker selectedItem沒有數據綁定

這裏是listPicker的XAML。

<toolkit:ListPicker x:Name="brewMethodList" HorizontalAlignment="Left" Margin="-2,24,0,0" VerticalAlignment="Top" Height="127" Width="164" BorderBrush="#FF162E3E" Foreground="Black" SelectionChanged="brewMethodSelectionChange" LostFocus="quantityInputLostFocus" Background="#FF5C97BF" > 
    <toolkit:ListPickerItem x:Name="manual_list" Content="Manual" Background="#FF5C97BF"/> 
    <toolkit:ListPickerItem x:Name="autoDrip_list" Content="Auto Drip" Background="#FF5C97BF"/> 
</toolkit:ListPicker> 

這裏是C#試圖訪問當前選擇的項目。

private void brewMethodSelectionChange(object sender, SelectionChangedEventArgs e) 
    { 
     if (brewMethodList.SelectedItem == manual_list) 
     { 
      brewMethod = MANUAL; 
     } 
     else 
     { 
      brewMethod = AUTO_DRIP; 
     } 
     update(); 
    } 

這只是一個簡化版本,但它拋出一個「System.NullReferenceException」,如果我將鼠標懸停我的鼠標移到「brewMethodList」它說空,和同樣超過懸停我的鼠標「manual_list。」

代表新人,我不完全瞭解數據綁定,如果這是我應該做的就讓我知道,但我認爲我可以在沒有它的情況下進行管理(另外我對於什麼它的能力)。 任何事情都非常感謝!我讀過幾乎每篇我能找到的文章。

回答

0

試試這個

private void brewMethodSelectionChange(object sender, SelectionChangedEventArgs e) 
    { 
     var brewMethodList = sender as ListPicker; 
     if (brewMethodList.SelectedItem == manual_list) 
     { 
      brewMethod = MANUAL; 
     } 
     else 
     { 
      brewMethod = AUTO_DRIP; 
     } 
     update(); 
    } 

但是,是的,它是更更好,如果你使用MVVM模式。這個鏈接應該是一個很好的參考,http://msdn.microsoft.com/en-us/magazine/hh852595.aspx

編輯:它也更好,如果你不通過控件的名稱檢查,一旦你實現MVVM模式,它會更清潔和更簡單的做,而不是做代碼背後的一切。 :)

+0

嗨科爾,它的工作? –

+0

非常感謝,並且確實有效,但之後發生了很多奇怪的事情。例如,如果我嘗試在if語句內更改textBlock的名稱,它只會起作用。如果我指定了兩個條件,則相對於只留下/ else來說。 – Cole

相關問題