我有一个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