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:x="#unknown">
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="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"
removed="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)
{
ListBoxItem ListBoxItem1 = new ListBoxItem();
ListBox1.Items.Add(ListBoxItem1);
}
private void btnEdit_Click(object sender, RoutedEventArgs e)
{
}
}
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