我有一個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。但是,他們的內容是空的。我現在正在研究這個問題。
很難理解,我認爲你應該正確地使用MVVM來實現它。綁定到ItemsSource,綁定DVSelection - 並處理視圖模型中的更改。不要直接處理代碼中的ItemsSource,因爲你可能會弄錯,綁定,更新等。 – NSGaga 2013-04-24 17:20:33
謝謝你的迴應。我將嘗試更好地解釋問題中正在發生的事情。我在代碼隱藏方面工作,因爲這在技術上是一個小對話框,將顯示在某個命令上(來自我的虛擬機)。我正在準備要提交的TextBoxes中的值。虛擬機不關心用戶在對話框中工作的內容;他只關心返回給他的東西。所以我正在準備對話框的代碼隱藏數據。在準備「SaveAndSubmit」數據後,我將與VM通信。或者這就是我至少計劃的。 – Joseph 2013-04-24 17:28:20