2013-04-24 43 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