PropertyChanged remains null #6855
-
class file |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
It actually works fine and getting invoked during debugging. Code under this spoiler,using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Input;
using CommunityToolkit.Mvvm.Input;
namespace WPF_Password_Generator.ViewModels
{
public class IndexViewModel : INotifyPropertyChanged
{
private readonly Models.Index _indexModel = new Models.Index();
public string TextContent
{
get
{
return _indexModel.textContent;
}
set
{
_indexModel.textContent = value;
OnPropertyChanged(nameof(TextContent));
}
}
public ICommand GenerateCommand { get; set; }
public IndexViewModel()
{
GenerateCommand = new RelayCommand(OnGenerateCommand);
}
private void OnGenerateCommand()
{
MessageBox.Show(TextContent); //Show current value
TextContent = "asdasdadasd"; //Replacing value, is this intended?
MessageBox.Show(TextContent); //Show replaced value
}
public event PropertyChangedEventHandler? PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string? propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
} A few more notes: Since you are using Code under this spoiler,ViewModel public class IndexViewModel : ObservableObject
{
public Models.Index IndexModel { get; }
public ICommand GenerateCommand { get; set; }
public IndexViewModel()
{
IndexModel = new Models.Index();
GenerateCommand = new RelayCommand(OnGenerateCommand);
}
private void OnGenerateCommand()
{
MessageBox.Show(IndexModel.TextContent); //Show current value
IndexModel.TextContent = "asdasdadasd"; //Replacing value, is this intended?
MessageBox.Show(IndexModel.TextContent); //Show replaced value
}
} Model public class Index : ObservableObject
{
private string _textContent = string.Empty;
public string TextContent
{
get => _textContent;
set => SetProperty(ref _textContent, value);
}
} Xaml <TextBox Grid.Row="0"
Grid.Column="2"
HorizontalAlignment="Stretch"
VerticalAlignment="Center"
Margin="10"
Text="{Binding IndexModel.TextContent, UpdateSourceTrigger=PropertyChanged}" |
Beta Was this translation helpful? Give feedback.
It actually works fine and getting invoked during debugging.
Or do you mean why the
TextContent
is not updated withindexViewModel.TextContent = "asdasdadasd";
from yourGenerate
class?Because you initialize new instances of
IndexViewModel
inside theGenerate
class instead of reusing the existing VM. I would also add, that yourICommand
implantation is wrong and I would recommend you to use theRelayCommand
from theCommunityToolkit.Mvvm
that you have installed.Here is a full working code.
Code under this spoiler,