IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Windows Presentation Foundation Discussion :

ListBox with DataTemplate and no Binding or a specific Binding in codebehind


Sujet :

Windows Presentation Foundation

  1. #1
    Membre à l'essai
    Homme Profil pro
    Consultant informatique
    Inscrit en
    Septembre 2011
    Messages
    10
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Consultant informatique
    Secteur : Finance

    Informations forums :
    Inscription : Septembre 2011
    Messages : 10
    Points : 14
    Points
    14
    Par défaut ListBox with DataTemplate and no Binding or a specific Binding in codebehind
    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

  2. #2
    Expert confirmé
    Inscrit en
    Avril 2008
    Messages
    2 564
    Détails du profil
    Informations personnelles :
    Âge : 64

    Informations forums :
    Inscription : Avril 2008
    Messages : 2 564
    Points : 4 441
    Points
    4 441
    Par défaut
    bonjour

    Citations by the gourou of Microsoft to meditate or cogitate :
    Both the Items and ItemsSource properties are defined by the ItemsControl class
    These two approaches to filling the ListBox adding items through the Add method of the Items property and setting ItemsSourceare mutually exclusive
    Il faut au prealable ajouter les data Items par code ...
    Ce scenario exige de gerer soi-meme la collection Items (addition,suppression ,modification)....
    poor translation in English...
    You need beforehand to fill the ListBox by adding the data items by code to the Items collection....
    This scenario need to manage the items collection by code...
    in btnEdit_Click method, I do not know how to change the text of the textbox located in the DataTemplate
    ContentPresenter of ListBoxItem with Itemplate do that...



    This sample use the following code behind .cs of class Data :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ComponentModel;
     
    namespace WpfListBoxCode
    {
        public class Data : INotifyPropertyChanged
        {
            public Data()
            {
                Name = "nothing";
                Comment = "no comment";
            }
            public Data(string n, string c)
                : this()
            {
                Name = n; 
                Comment = c;
            }
            private string name;
            public string Name
            {
                get { return name; }
                set { name = value; RaiseDataChanged("Name"); }
            }
     
            private string comment;
            public string Comment
            {
                get { return comment; }
                set { comment = value; RaiseDataChanged("Comment"); }
            }
     
     
     
            public event PropertyChangedEventHandler PropertyChanged;
            private void RaiseDataChanged(string nameProp)
            {
                PropertyChangedEventHandler h = PropertyChanged;
                if (h != null)
                    h(this, new PropertyChangedEventArgs(nameProp));
            }
     
        }
    }
    code behind xaml of form user :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
     
     
    <Window x:Class="WpfListBoxCode.Window2"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="Window2" Height="300" Width="300">
        <Window.Resources>
        <DataTemplate x:Key="DataTemplate1">
            <Grid Height="100" Width="500">
                <Grid.RowDefinitions>
                    <RowDefinition></RowDefinition>
                    <RowDefinition></RowDefinition>
                </Grid.RowDefinitions>
                <Grid Grid.Row="0">
                    <Button 
                        x:Name="btnEdit" Content="Edit" ToolTip="Click to change the text"
                        Width="40"
                        Focusable="False"
                        IsTabStop="False"
                        IsEnabled="{Binding Path=IsSelected,RelativeSource={RelativeSource AncestorType=ListBoxItem}}"
                        Click="btnEdit_Click"/>
                </Grid>
                <Grid Grid.Row="1">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition></ColumnDefinition>
                        <ColumnDefinition></ColumnDefinition>
                    </Grid.ColumnDefinitions>
                    <TextBox
                        x:Name="tbName"
                        Grid.Column="0"
                        Text="{Binding Name}"
                        Width="500" TextWrapping="Wrap" AcceptsReturn="True" AcceptsTab="True"
                        ScrollViewer.VerticalScrollBarVisibility="Visible"
                        ScrollViewer.HorizontalScrollBarVisibility="Disabled">
                    </TextBox>
                    <TextBox
                        x:Name="tbComment"
                        Grid.Column="1"
                        Text="{Binding Comment}"
                        Width="500" TextWrapping="Wrap" AcceptsReturn="True" AcceptsTab="True"
                        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="AddItem" VerticalAlignment="Center"
                    Width="75" Margin="20,0,0,0" 
                    Click="AddItem_Click"/>
            </Grid>
            <Grid DockPanel.Dock="Top" Height="50" >
                <Button 
                    Content="Remove Item" Height="23" HorizontalAlignment="Left" 
                    Name="RemoveItem" VerticalAlignment="Center"
                    Width="75" Margin="20,0,0,0" Click="RemoveItem_Click"/>
            </Grid>
            <Grid DockPanel.Dock="Top" Height="50" >
                <TextBlock x:Name="tbShow"
                       DockPanel.Dock="Bottom"  
                       Foreground="Red" 
                       Background="Aquamarine" 
                       Height="50"
                      Text="{Binding ElementName=ListBox1,Path=SelectedValue}" >
                </TextBlock>
            </Grid>
     
            <ScrollViewer 
                DockPanel.Dock="Top" 
                HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Disabled">
                <Grid HorizontalAlignment="Left" Width="500">
                    <ListBox 
                        x:Name="ListBox1" 
                        HorizontalAlignment="Left"
                        BorderBrush="Transparent" 
                        Background="Transparent" 
                        ItemTemplate="{StaticResource DataTemplate1}"
                        IsSynchronizedWithCurrentItem="True"
                        SelectedValuePath="Comment"
                        SelectedValue="Comment"
                        ScrollViewer.HorizontalScrollBarVisibility="Disabled">
                    </ListBox>
                </Grid>
            </ScrollViewer>
     
        </DockPanel>
    </Window>
    code behind .cs of from user:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Shapes;
     
    namespace WpfListBoxCode
    {
        /// <summary>
        /// Logique d'interaction pour Window2.xaml
        /// </summary>
        public partial class Window2 : Window
        {
            private List<Data> dataList = null;
            private Data itemData = null;
            public Window2()
            {
                InitializeComponent();
                dataList = new List<Data>();
     
     
            }
     
     
            private int count;
            private void AddItem_Click(object sender, RoutedEventArgs e)
            {
                count++;
                itemData = new Data("item" + count.ToString(), "comment..." + count.ToString());
                //some synchronization to dataList
                dataList.Add(itemData);
     
     
                ListBox1.Items.Add(itemData);
                ListBox1.Items.Refresh();
     
     
            }
     
            private void RemoveItem_Click(object sender, RoutedEventArgs e)
            {
                if (ListBox1.SelectedItem != null)
                {
                    dataList.RemoveAt(ListBox1.SelectedIndex); 
                    ListBox1.Items.RemoveAt(ListBox1.SelectedIndex);
     
                }
            }
            private void btnEdit_Click(object sender, RoutedEventArgs e)
            {
                if (ListBox1.Items.CurrentItem == null) return;
                // Getting the currently selected ListBoxItem
                // Note that the ListBox must have IsSynchronizedWithCurrentItem set to True for this to work
                ListBoxItem myListBoxItem =
                    (ListBoxItem)(ListBox1.ItemContainerGenerator.ContainerFromItem(ListBox1.Items.CurrentItem));
     
                // Getting the ContentPresenter of myListBoxItem
                ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(myListBoxItem);
     
                // Finding textBlock from the DataTemplate that is set on that ContentPresenter
                DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;
                TextBox myTextBox = (TextBox)myDataTemplate.FindName("tbComment", myContentPresenter);
     
                // Do something to the DataTemplate-generated TextBlock
                MessageBox.Show("The text of the TextBlock of the selected list item: "
                    + myTextBox.Text);
     
                //some synchronization to dataList
                dataList[ListBox1.Items.CurrentPosition].Comment = myTextBox.Text;
     
            }
     
            private childItem FindVisualChild<childItem>(DependencyObject obj) where childItem : DependencyObject
            {
                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
                {
                    DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                    if (child != null && child is childItem)
                        return (childItem)child;
                    else
                    {
                        childItem childOfChild = FindVisualChild<childItem>(child);
                        if (childOfChild != null)
                            return childOfChild;
                    }
                }
                return null;
            }
     
     
        }
    }
    bon code......

  3. #3
    Membre à l'essai
    Homme Profil pro
    Consultant informatique
    Inscrit en
    Septembre 2011
    Messages
    10
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Consultant informatique
    Secteur : Finance

    Informations forums :
    Inscription : Septembre 2011
    Messages : 10
    Points : 14
    Points
    14
    Par défaut ListBox with DataTemplate and no Binding or a specific Binding in codebehind
    bonjour
    Merci beaucoup, vous avez fait un excellent travail pour moi et cela va beaucoup m'aider pour la suite de mon développement,
    parce que bien sûr dans mon projet final, il y aura dans chaque Item de nombreux contrôles (TextBlock , ComboBox TextBox)
    Avec les bonnes bases que vous m'avez donné, je vais pouvoir continuer la suite de la programmation de ma ListBox
    Avec votre solution, j'ai accès à la fois à la ListBox et au ListBoxItem séléctionné
    Encore une fois , merci de votre aide
    Cordialement

    hello
    Thank you, you did a great job for me and it will help me a lot for the rest of my development,
    because, of course, in my final project, there will be in each Item many controls (TextBlock, TextBox ComboBox)
    With the right foundation that you gave me, I'm going to continue the programming of my ListBox
    With your solution, I have access to the ListBox and the selected ListBoxItem
    Again, thank you for your help
    Best regards

Discussions similaires

  1. Trouble with setting both DataTemplate and ControlTemplate to Map Pushpins in WPF
    Par totow dans le forum Windows Presentation Foundation
    Réponses: 0
    Dernier message: 15/06/2013, 17h38
  2. Binding listbox avec datatemplate et récupération de valeur
    Par tom741 dans le forum Windows Presentation Foundation
    Réponses: 3
    Dernier message: 24/03/2009, 18h02
  3. [C#] Calendar Popup with TextBox and Image?
    Par Nadaa dans le forum ASP.NET
    Réponses: 15
    Dernier message: 04/02/2009, 11h59
  4. Indy TIdFTP : Please login with USER and PASS.
    Par sinfoni dans le forum Composants VCL
    Réponses: 3
    Dernier message: 19/03/2008, 08h15

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo