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

C# Discussion :

WPF : TextBlock et Label non mis à jour après modification de la source


Sujet :

C#

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre confirmé
    Profil pro
    Inscrit en
    Décembre 2004
    Messages
    179
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2004
    Messages : 179
    Par défaut WPF : TextBlock et Label non mis à jour après modification de la source
    Bonjour,
    Je suis en train de plus ou moins débuter en WPF et j'en suis au Data Binding. Je suis sur un exemple de https://wpf-tutorial.com/fr/38/data-...x-changements/
    Cela fonctionne très bien, mais moi je voudrais rafraichir un TextBlock et un Label après que la source de données ait changé, mais cela ne fonctionne pas. Est-ce que quelqu'un pourrait me dire pourquoi, parce que je pédale un peu dans la semoule depuis un bon moment :-(
    Voici la partie XAML :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
        <Grid Margin="10">
            <Button Name="btnAddUser" Click="btnAddUser_Click" Margin="650,0,0,371">Add user</Button>
            <Button Name="btnChangeUser" Click="btnChangeUser_Click" Margin="650,59,0,313">Change user</Button>
            <Button Name="btnDeleteUser" Click="btnDeleteUser_Click" Margin="650,116,0,255">Delete user</Button>
            <ListBox Name="lbUsers" DisplayMemberPath="Name" BorderBrush="Black" BorderThickness="1 1 1 1" Height="192" Width="300" Margin="10,15,470,207" ></ListBox>
            <TextBox x:Name="tbNom" HorizontalAlignment="Left" Margin="52,287,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="152" Height="25" FontSize="16"/>
            <TextBlock x:Name="tbCopie" VerticalAlignment="Top" Width="202" Height="25" FontSize="16" Margin="289,282,289,0" Text="{Binding Path=users[1].Name}" />
            <Label x:Name="lblCopie" BorderBrush="Black" BorderThickness="1 1 1 1"  Content="{Binding Path=users[1].Name}" HorizontalAlignment="Left" Margin="273,339,0,0" VerticalAlignment="Top" Height="37" Width="140"/>
        </Grid>
    Et là la partie Code Behind :
    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
     
    namespace WpfTuto
    {
        /// <summary>
        /// Logique d'interaction pour WinUpdateSource.xaml
        /// </summary>
        public partial class WinUpdateSource : Window
        {
            public class User : INotifyPropertyChanged
            {
                private string name;
                public string Name
                {
                    get { return this.name; }
                    set
                    {
                        if (this.name != value)
                        {
                            this.name = value;
                            this.NotifyPropertyChanged("Name");
                        }
                    }
                }
     
                public event PropertyChangedEventHandler PropertyChanged;
     
                public void NotifyPropertyChanged(string propName)
                {
                    if (this.PropertyChanged != null)
                        this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
                }
            }
            // private List<User> users = new List<User>();
            private ObservableCollection<User> users = new ObservableCollection<User>();
            public WinUpdateSource()
            {
                InitializeComponent();
                users.Add(new User() { Name = "John Doe" });
                users.Add(new User() { Name = "Jane Doe" });
                tbCopie.Text = users[1].Name;
                lblCopie.Content = users[1].Name;
                lbUsers.ItemsSource = users;
            }
            private void btnAddUser_Click(object sender, RoutedEventArgs e)
            {
     
                users.Add(new User() { Name = tbNom.Text });
            }
     
            private void btnChangeUser_Click(object sender, RoutedEventArgs e)
            {
                if (lbUsers.SelectedItem != null)
                    (lbUsers.SelectedItem as User).Name = "Random Name";
            }
     
            private void btnDeleteUser_Click(object sender, RoutedEventArgs e)
            {
                if (lbUsers.SelectedItem != null)
                    users.Remove(lbUsers.SelectedItem as User);
            }
        }
    }
    Merci d'avance pour votre aide.

  2. #2
    Membre Expert
    Homme Profil pro
    edi
    Inscrit en
    Juin 2007
    Messages
    941
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Gironde (Aquitaine)

    Informations professionnelles :
    Activité : edi

    Informations forums :
    Inscription : Juin 2007
    Messages : 941
    Par défaut
    En fait aucun de tes binding n'est correctement branché, tu en as juste l'impression parce-que dans le constructeur de la fenêtre tu affectes les propriétés de tes composants, mais sans passer par un binding.

  3. #3
    Membre régulier
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Mai 2021
    Messages
    10
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 46
    Localisation : France, Gard (Languedoc Roussillon)

    Informations professionnelles :
    Activité : Développeur .NET
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2021
    Messages : 10
    Par défaut
    Bonjour,

    Il date un peu mais tous les concepts WPF MVVM sont expliqués :

    https://japf.developpez.com/tutoriel...-et-testables/

  4. #4
    Membre confirmé
    Profil pro
    Inscrit en
    Décembre 2004
    Messages
    179
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2004
    Messages : 179
    Par défaut
    Bonjour,
    Merci pour vos réponses je vais lire attentivement le support proposé.

  5. #5
    Membre Expert
    Homme Profil pro
    edi
    Inscrit en
    Juin 2007
    Messages
    941
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Gironde (Aquitaine)

    Informations professionnelles :
    Activité : edi

    Informations forums :
    Inscription : Juin 2007
    Messages : 941
    Par défaut
    Ça fait un moment que je n'ai pas fait de WPF, mais j'ai tenté de préparer un exemple à peu près complet. À noter que j'ai importé le package CommunityToolkit.Mvvm (héritier de MvvmLight de Laurent Bugnion).

    Le fichier de code avec la fenêtre et un view model :

    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
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    using CommunityToolkit.Mvvm.Input;
    using System.Collections.ObjectModel;
    using System.ComponentModel;
    using System.Runtime.CompilerServices;
    using System.Windows;
    using System.Windows.Input;
     
    namespace D2174215
    {
    	/// <summary>
    	/// Interaction logic for MainWindow.xaml
    	/// </summary>
    	public partial class MainWindow : Window
    	{
    		public MainWindow()
    		{
    			InitializeComponent();
    		}
     
    		private void MainViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
    		{
    			if (sender is not MainViewModel mvm) return;
    			if (e.PropertyName == nameof(MainViewModel.PlayerName) && mvm.PlayerName == string.Empty)
    				PlayerName.Focus();
    		}
    	}
     
    	public class MainViewModel : CommunityToolkit.Mvvm.ComponentModel.ObservableObject
    	{
    		public MainViewModel()
    		{
    			Players = new(_players);
     
    			_addPlayerCommand = new RelayCommand(AddPlayer, CanAddPlayer);
    			_removePlayerCommand = new RelayCommand<Player>(RemovePlayer);
    		}
     
    		public string? PlayerName
    		{
    			get => _playerName;
    			set
    			{
    				if (SetProperty(ref _playerName, value))
    					_addPlayerCommand.NotifyCanExecuteChanged();
    			}
    		}
    		private string? _playerName;
     
    		public ReadOnlyObservableCollection<Player> Players { get; }
    		private readonly ObservableCollection<Player> _players = [];
     
    		public ICommand AddPlayerCommand => _addPlayerCommand;
    		private readonly RelayCommand _addPlayerCommand;
    		public void AddPlayer()
    		{
    			if (string.IsNullOrWhiteSpace(PlayerName)) return;
    			_players.Add(new Player { Name = PlayerName.Trim() });
    			PlayerName = string.Empty;
    		}
    		public bool CanAddPlayer() => !string.IsNullOrWhiteSpace(PlayerName);
     
    		public ICommand RemovePlayerCommand => _removePlayerCommand;
    		private readonly RelayCommand<Player> _removePlayerCommand;
    		public void RemovePlayer(Player? player)
    		{
    			if (player is not null)
    				_players.Remove(player);
    		}
     
    		public ICommand IncreaseScoreCommand => _increaseScoreCommand;
    		private readonly RelayCommand<Player> _increaseScoreCommand = new(IncreaseScore);
    		private static void IncreaseScore(Player? player)
    		{
    			if (player is not null)
    				player.Score++;
    		}
     
    		public ICommand DecreaseScoreCommand => _decreaseScoreCommand;
    		private readonly RelayCommand<Player> _decreaseScoreCommand = new(DecreaseScore);
    		private static void DecreaseScore(Player? player)
    		{
    			if (player is not null)
    				player.Score--;
    		}
    	}
     
    	public class Player : INotifyPropertyChanged
    	{
    		public string Name
    		{
    			get => _name;
    			set
    			{
    				if (_name == value) return;
    				_name = value ?? string.Empty;
    				OnPropertyChanged();
    			}
    		}
    		private string _name = string.Empty;
     
    		public int Score
    		{
    			get => _score;
    			set
    			{
    				if (_score == value) return;
    				_score = value;
    				OnPropertyChanged();
    			}
    		}
    		private int _score;
     
    		private void OnPropertyChanged([CallerMemberName] string? propertyName = null) =>
    			PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
     
    		public event PropertyChangedEventHandler? PropertyChanged;
    	}
    }
    Le code xaml pour la fenêtre :

    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
    <Window x:Class="D2174215.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:system="clr-namespace:System;assembly=mscorlib"
            xmlns:local="clr-namespace:D2174215"
            mc:Ignorable="d"
            Title="Scoreboard" Height="450" Width="800">
        <Window.Resources>
            <ResourceDictionary>
                <system:String x:Key="Title">Scoreboard</system:String>
                <system:String x:Key="Player_name">Player name:</system:String>
                <system:String x:Key="Add_player">Add player</system:String>
                <system:String x:Key="Remove">Remove</system:String>
                <system:String x:Key="Number_of_players">Number of players:</system:String>
            </ResourceDictionary>
        </Window.Resources>
        <Window.DataContext>
            <local:MainViewModel PropertyChanged="MainViewModel_PropertyChanged" />
        </Window.DataContext>
        <DockPanel>
            <TextBlock DockPanel.Dock="Top" Text="{StaticResource ResourceKey=Title}" FontSize="16" FontWeight="Bold" Padding="5" TextAlignment="Center"/>
            <Grid DockPanel.Dock="Top" Margin="5">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="100"/>
                    <ColumnDefinition MinWidth="150"/>
                    <ColumnDefinition Width="100"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <TextBlock Grid.Column="0" Text="{StaticResource ResourceKey=Player_name}" />
                <TextBox Grid.Column="1" Text="{Binding PlayerName, UpdateSourceTrigger=PropertyChanged}" x:Name="PlayerName">
                    <TextBox.InputBindings>
                        <KeyBinding Key="Return" Command="{Binding AddPlayerCommand}" />
                    </TextBox.InputBindings>
                </TextBox>
                <Button Grid.Column="2" Command="{Binding AddPlayerCommand}" Margin="5,0,5,0" Content="{StaticResource ResourceKey=Add_player}">
                    <Button.InputBindings>
                        <KeyBinding Key="Return" Command="{Binding AddPlayerCommand}" />
                    </Button.InputBindings>
                </Button>
            </Grid>
            <StackPanel DockPanel.Dock="Bottom" Margin="10,5,10,10" Orientation="Horizontal">
                <TextBlock Text="{StaticResource ResourceKey=Number_of_players}" Margin="0,0,10,0"/>
                <TextBlock Text="{Binding Players.Count}"/>
            </StackPanel>
            <ListView Margin="5" ItemsSource="{Binding Players}">
                <d:ListView.ItemsSource>
                    <x:Array Type="local:Player">
                        <local:Player Name="Hector"/>
                        <local:Player Name="Deliah"/>
                    </x:Array>
                </d:ListView.ItemsSource>
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition  Width="100" />
                                <ColumnDefinition Width="20" />
                                <ColumnDefinition  Width="20"/>
                                <ColumnDefinition Width="20" />
                                <ColumnDefinition MinWidth="100" />
                                <ColumnDefinition Width="100" />
                            </Grid.ColumnDefinitions>
                            <TextBlock Grid.Column="0" Text="{Binding Name}" />
                            <Button Grid.Column="1"
                                    Content="-"
                                    Command="{Binding DataContext.DecreaseScoreCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}"
                                    CommandParameter="{Binding}" />
                            <TextBlock Grid.Column="2" Text="{Binding Score}" TextAlignment="Left" Padding="5" />
                            <Button Grid.Column="3"
                                    Content="+"
                                    Command="{Binding DataContext.IncreaseScoreCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}"
                                    CommandParameter="{Binding}" />
                            <Border Grid.Column="4" />
                            <Button Grid.Column="5" Margin="10,0,0,0"
                                    Content="{StaticResource ResourceKey=Remove}"
                                    Command="{Binding DataContext.RemovePlayerCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}"
                                    CommandParameter="{Binding}" />
                        </Grid>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </DockPanel>
    </Window>

  6. #6
    Expert confirmé
    Avatar de popo
    Homme Profil pro
    Analyste programmeur Delphi / C#
    Inscrit en
    Mars 2005
    Messages
    2 972
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Analyste programmeur Delphi / C#
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mars 2005
    Messages : 2 972
    Par défaut
    C'est dommage d'utiliser CommunityToolkit.Mvvm et de coder manuellement les mécaniques qu'il propose.
    https://learn.microsoft.com/en-us/do...ators/overview

Discussions similaires

  1. Réponses: 2
    Dernier message: 23/04/2015, 13h10
  2. [AC-2007] Mise à jour après modification données
    Par Kevin_strickland dans le forum Macros Access
    Réponses: 3
    Dernier message: 24/07/2013, 08h40
  3. Réponses: 2
    Dernier message: 08/10/2010, 20h49
  4. [CR 9] Nom de table pas mis à jour après changement de la source de données
    Par zodeno dans le forum Connectivité
    Réponses: 3
    Dernier message: 29/09/2009, 13h36
  5. Vue non mise à jour après modification d'une table
    Par cybernet35 dans le forum MS SQL Server
    Réponses: 3
    Dernier message: 19/01/2006, 13h54

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