2013-04-24 71 views
0

我有一個ListBox顯示動態數字TextBox es。用戶將在這些框中輸入文本。當點擊提交按鈕,我需要能夠訪問用戶輸入文本,應在ListBox.Items,就像這樣:列表框不跟蹤用戶輸入

//Called on Submit button click 
    private void SaveAndSubmit(object sender, ExecutedRoutedEventArgs e) 
    { 
     var bounds = MyListBox.Items; 
    } 

MyListBox.Items後,我初步確定ItemsSource不會改變,在這裏:

//Field declaration 
    //Bounds is containing a group of strings that represent the boundaries 
    //for a contour plot. The min/max values are stored at the front and back 
    //of the group. However, there can be any number of dividers in between. 
    public ObservableCollection<string> Bounds { get; set; } 

    ... 
    //Initialize Bounds in the constructor 

    //Called when the selected item for DVList (an unrelated ListBox) is changed 
    private void DVSelectionChanged(object sender, SelectionChangedEventArgs e) 
    { 
     var selectedDV = DVList.SelectedItem as DVWrapper; 
     if (selectedDV != null) 
     { 
      //Setting min/max 
      Bounds[0] = selectedDV.MinValue; 
      Bounds[Bounds.Count - 1] = selectedDV.MaxValue; 

      MyListBox.ItemsSource = Bounds; 
     } 
    } 

我的XAML看起來像這樣:

<Window.Resources> 
    <Style x:Key="BoundsStyle" TargetType="{x:Type ListBoxItem}"> 
     <Setter Property="ContentTemplate"> 
      <Setter.Value> 
       <DataTemplate> 
        <Grid> 
         ... 
         <TextBox/> 
        </Grid> 
       </DataTemplate> 
      </Setter.Value> 
     </Setter> 
     <Setter Property="Focusable" Value="False"/> 
    </Style> 
</Window.Resources> 

... 

       <ListBox Name="MyListBox" 
         ItemContainerStyle="{StaticResource BoundsStyle}"/> 

所以當SaveAndSubmit被調用時,bounds結果是我最初設置在DVSelectionChanged。換句話說,列表框不會根據用戶輸入到列表框中的文本框的內容進行更新。我如何獲得更新的ListBoxItem?我認爲我的問題與this類似,但目前它不適合我。

當我在調試器中單步執行時,我可以獲得個人ListBoxItem s。但是,他們的內容是空的。我現在正在研究這個問題。

+0

很難理解,我認爲你應該正確地使用MVVM來實現它。綁定到ItemsSource,綁定DVSelection - 並處理視圖模型中的更改。不要直接處理代碼中的ItemsSource,因爲你可能會弄錯,綁定,更新等。 – NSGaga 2013-04-24 17:20:33

+0

謝謝你的迴應。我將嘗試更好地解釋問題中正在發生的事情。我在代碼隱藏方面工作,因爲這在技術上是一個小對話框,將顯示在某個命令上(來自我的虛擬機)。我正在準備要提交的TextBoxes中的值。虛擬機不關心用戶在對話框中工作的內容;他只關心返回給他的東西。所以我正在準備對話框的代碼隱藏數據。在準備「SaveAndSubmit」數據後,我將與VM通信。或者這就是我至少計劃的。 – Joseph 2013-04-24 17:28:20

回答

0

您需要綁定文本框的內容。

<TextBox/>需要改變,以<TextBox Content="{Binding}"/>

而是遵循MVVM否則將很難找到這些錯誤。

+0

TextBox沒有內容,所以我使用了Text屬性。我綁定什麼?當我剛使用'「{Binding}」'時,我收到一個關於需要Path的雙向綁定的錯誤。 – Joseph 2013-04-24 17:33:00

+0

{綁定}意味着綁定到對象本身。由於您的observablecollection是字符串,因此沒有我們想要綁定的字符串屬性。我們需要綁定到字符串本身。確定文本屬性是正確的。可能2路綁定需要一個屬性。所以你需要創建一個對象而不是字符串,並將文本框綁定到它的屬性。 – 2013-04-24 18:00:18

+0

這樣做。謝謝你的答案。我將繼續努力。我仍然不相信MVVM會解決/避免這個特殊問題。 – Joseph 2013-04-24 18:34:51