Bind textbox list inside listbox in wpf

NewInDevelopment picture NewInDevelopment · Jun 3, 2014 · Viewed 7.2k times · Source

I have to make listbox with textbox in it... and it has to be dynamic. I have observable collection in code behind and I want to bind that for listbox. I want dynamic listbox and this list should have editable textbox in it. So, basically I want to bind multiplr textbox from listbox. Any help would be appreciated

<ListBox HorizontalAlignment="Left" Name="ListTwo" Height="100" Margin="286.769,165.499,0,0" VerticalAlignment="Top" Width="100" ItemsSource="{Binding Source=obs}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBox Name="TextBoxList"></TextBox>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

By doing this, I have number of textbox same as items in observable collection but textbox's text is not set up.

Answer

Sheridan picture Sheridan · Jun 3, 2014

If the items in your ObservableCollection are just plain strings, then you can data bind to the whole string value like this:

<ListBox Name="ListTwo" ItemsSource="{Binding Source=obs}" ... >
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBox Name="TextBoxList" Text="{Binding}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

From the Binding.Path Property page on MSDN:

Optionally, a period (.) path can be used to bind to the current source. For example, Text="{Binding}" is equivalent to Text="{Binding Path=.}".

Note that if you had some objects with properties in the collection, then @nit's answer would have been correct as you would need to reference the relevant property name:

<ListBox Name="ListTwo" ItemsSource="{Binding Source=obs}" ... >
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBox Name="TextBoxList" Text="{Binding PropertyName}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>