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#

  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
    3 012
    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 : 3 012
    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

  7. #7
    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
    J'ai surtout utilis� CommunityToolkit.Mvvm pour les RelayCommand. J'ai vu qu'il y avait des attributs pour utiliser des source generators, mais comme il d�bute avec WPF j'ai pr�f�r� laiss� apparents certains m�canismes. C'est pour �a que MainViewModel h�rite de ObservableObject mais que pour Player j'ai impl�ment� INotifyPropertyChanged explicitement, �a donne une id�e de ce qui se passe en coulisse. Une fois qu'il aura int�gr� ces bases il pourra utiliser des outils plus avanc�s.

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. 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