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
TextContentis not updated withindexViewModel.TextContent = "asdasdadasd";from yourGenerateclass?Because you initialize new instances of
IndexViewModelinside theGenerateclass instead of reusing the existing VM. I would also add, that yourICommandimplantation is wrong and I would recommend you to use theRelayCommandfrom theCommunityToolkit.Mvvmthat you have installed.Here is a full working code.
Code under this spoiler,