Hello

I work in .Net C# WPF and I want to create a ListBox with a DataTemplate to formating many data to read and write
But I wish also manipulate the elements of the ListBox independently (edit the TextBox ; position on an item)
so, I does not wish to use a Binding with an ObservableCollection

I put here a deliberately simplified example:

Xaml :

<Window x:Class="TestListBox.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">

<Window.Resources>
<DataTemplate x:Key="DataTemplate1">
<Grid Height="100" Width="500">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="400"/>
</Grid.ColumnDefinitions>
<Grid Grid.Row="0">
<Button x:Name="btnEdit" Content="Edit" ToolTip="Click to change the text"
Width="40"
Focusable="False"
IsTabStop="False"
Click="btnEdit_Click"/>
</Grid>
<Grid Grid.Row="1">
<TextBox
Width="500" TextWrapping="Wrap" AcceptsReturn="True" AcceptsTab="True"
Text="{Binding Comment1}"
ScrollViewer.VerticalScrollBarVisibility="Visible"
ScrollViewer.HorizontalScrollBarVisibility="Disabled">
</TextBox>
</Grid>
</Grid>
</DataTemplate>
</Window.Resources>

<DockPanel>
<Grid DockPanel.Dock="Top" Height="50" >
<Button Content="Add Item" Height="23" HorizontalAlignment="Left" Name="AddItem1" VerticalAlignment="Center"
Width="75" Margin="20,0,0,0" Click="AddItem1_Click"/>
</Grid>
<ScrollViewer HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Disabled">
<Grid HorizontalAlignment="Left" Width="500">
<ListBox x:Name="ListBox1" ItemTemplate="{StaticResource DataTemplate1}" ItemsSource="{Binding}"
HorizontalAlignment="Left"
BorderBrush="Transparent"
Background="Transparent"
ScrollViewer.HorizontalScrollBarVisibility="Disabled">
</ListBox>
</Grid>
</ScrollViewer>
</DockPanel>
</Window>


Code :

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();

DataContext = this;
}

private void AddItem1_Click(object sender, RoutedEventArgs e)
{
// Add Item
ListBoxItem ListBoxItem1 = new ListBoxItem();

// Create the ListBoxItem (which DataTemplate is DataTemplate1
// ??? ListBoxItem1.Comment1 = "My Text";

ListBox1.Items.Add(ListBoxItem1);
}

private void btnEdit_Click(object sender, RoutedEventArgs e)
{
// modification of all data contained in the DataTemplate (currently I have put only comment1 for simplification)

// ??? Comment1 = "My new text";
}
}


In AddItem1_Click method, I do not know how to create a ListBoxItem that uses the DataTemplate

in btnEdit_Click method, I do not know how to change the text of the textbox located in the DataTemplate

Binding done a lot of work internally and as soon as one wants to do something specific, it becomes very difficult to do.

Can you resolve my problem ?
thanks in advance