列表框不跟踪用户输入

时间:2013-04-24 16:00:45

标签: c# wpf listbox code-behind

我有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。但是,他们的内容是空的。我现在正在研究它。

1 个答案:

答案 0 :(得分:0)

您需要绑定文本框的内容。

<TextBox/>需要更改为<TextBox Content="{Binding}"/>

但是遵循MVVM,否则很难找到这些错误。