Как связать изменение свойства в моем окне, когда изменение происходит в другом классе?C#

Место общения программистов C#
Ответить
Anonymous
 Как связать изменение свойства в моем окне, когда изменение происходит в другом классе?

Сообщение Anonymous »

Я хочу, чтобы свойство UserBalance менялось в окне, но это изменение происходит в другом классе.
Это мой банковский счет.cs, где у меня есть баланс, и он изменяется с помощью таких методов, как депозит и т. д.:
public class BankAccount : INotifyPropertyChanged
{
private decimal _balance;
public decimal Balance
{
get { return _balance; }
private set
{
if (_balance != value)
{
_balance = value;
NotifyPropertyChanged();
}
}

}

public event PropertyChangedEventHandler? PropertyChanged;

private void NotifyPropertyChanged([CallerMemberName] string? propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}

Это Dashboard.xaml.cs, где я хочу, чтобы изменение баланса отображалось в текстовом блоке окна:
public partial class Dashboard : Window, INotifyPropertyChanged
{
private static readonly CultureInfo EuroInfo = new("de-DE");
private User? _currentUser;
private UserRepository? _allUsers;
private decimal _userBalance;

public decimal UserBalance
{
get => _userBalance;
set
{
if (_userBalance != value)
{
_userBalance = value;
NotifyPropertyChanged();
}
}
}

public event PropertyChangedEventHandler? PropertyChanged;
private void NotifyPropertyChanged(string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

public Dashboard(User currentUser, UserRepository allUsers)
{
InitializeComponent();
this.DataContext = this;

try
{
this.Title = currentUser.FullName;
_currentUser = currentUser;
_allUsers = allUsers;

UserBalance = _currentUser?.BankAccount?.Balance ?? 0m;
}
catch (NullReferenceException e)
{
MessageBox.Show(e.StackTrace);
}
}
}

Вот как выглядит мой Dashboard.xaml.cs:
public partial class Dashboard : Window
{
//i save the user and the list to pass their values to other windows as well
private User? _currentUser;
private UserRepository? _allUsers;

//i create the balance prop so we can see the changes in the window
private decimal _userBalance;

public decimal UserBalance
{
get => _userBalance;
set
{
_userBalance = value;
}
}

public Dashboard(User currentUser, UserRepository allUsers)
{
InitializeComponent();
this.DataContext = currentUser;

try
{
this.Title = currentUser.FullName;
_currentUser = currentUser;
_allUsers = allUsers;

UserBalance = _currentUser?.BankAccount?.Balance ?? 0m;
if (currentUser.BankAccount != null)
_currentUser.BankAccount.PropertyChanged += BankAccount_PropertyChanged;

}
catch (NullReferenceException e)
{
MessageBox.Show(e.StackTrace);
}
catch (Exception e)
{
MessageBox.Show(e.GetType() + e.StackTrace);
}
}

private void BankAccount_PropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (e == null || e.PropertyName == null || e.PropertyName == nameof(BankAccount.Balance))
Dispatcher.Invoke(() => UserBalance = _currentUser?.BankAccount?.Balance ?? 0m);
}


Подробнее здесь: https://stackoverflow.com/questions/798 ... in-another
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»