Проблема с моей MVVM, я не могу изменить реквизиты ViewModel из другой ViewModel, пользовательский интерфейс не обновляеC#

Место общения программистов C#
Ответить Пред. темаСлед. тема
Anonymous
 Проблема с моей MVVM, я не могу изменить реквизиты ViewModel из другой ViewModel, пользовательский интерфейс не обновляе

Сообщение Anonymous »

У меня много проблем с моей MVVM, я не могу передать какие-либо реквизиты, или если я все еще передаю их из ViewModel в другую ViewModel, пользовательский интерфейс все равно не обновляется.
Например, здесь:
Мои файлы xaml:





















Мои классы ViewModel:
namespace InteWPF.ViewModel.Components
{
public class PlotViewModel : ObservableObject, IDisposable
{
// ====================== About Plot ======================
private DispatcherTimer _timer;
private bool _isTracking;
private bool _isPaused;
private bool _locked = false;
private bool _stopAll = false;
private bool _isLocked = false;
private DataPoint _nearestPoint = new DataPoint(0,0);
private DataPoint near = new DataPoint(0, 0);
private ScreenPoint mouseDownPoint;
private int waveLengthIndex;
private bool mouseWavelengthClick = false;

public PlotViewModel()
{
SpectralPlotModel = new PlotModel
{
Title = "Sweep",
Background = OxyColors.Transparent,
TextColor = OxyColors.White,
PlotAreaBorderColor = OxyColors.White
};

SpectralPlotModel.Axes.Add(new LinearAxis
{
Position = AxisPosition.Bottom,
Title = "Wavelength",
TitleColor = OxyColors.White,
AxislineColor = OxyColors.White,
TextColor = OxyColors.White,
TicklineColor = OxyColors.White,
StringFormat = "0.###",
Minimum = 1546,
Maximum = 1558
});

SpectralPlotModel.Axes.Add(new LinearAxis
{
Position = AxisPosition.Left,
Title = "Arbitrary Units",
TitleColor = OxyColors.White,
AxislineColor = OxyColors.White,
TextColor = OxyColors.White,
TicklineColor = OxyColors.White,
StringFormat = "0.###",
Minimum = 0,
Maximum = 5,
});

SpectralPlotModel.Series.Add(new LineSeries
{
Title = "Data",
Color = OxyColors.White,
MarkerFill = OxyColors.White,
MarkerType = MarkerType.None,
LineStyle = LineStyle.Solid,
StrokeThickness = 2,
});

SpectralPlotModel.MouseDown += MyPlotModel_MouseDown;

SpectralAEPlotModel = new PlotModel
{
Title = "AE",
Background = OxyColors.Transparent,
TextColor = OxyColors.White,
PlotAreaBorderColor = OxyColors.White
};

SpectralAEPlotModel.Axes.Add(new LinearAxis
{
Position = AxisPosition.Bottom,
Title = "Time",
TitleColor = OxyColors.White,
AxislineColor = OxyColors.White,
TextColor = OxyColors.White,
TicklineColor = OxyColors.White,
StringFormat = "0.###",
});

SpectralAEPlotModel.Axes.Add(new LinearAxis
{
Position = AxisPosition.Left,
Title = "Amplitude",
TitleColor = OxyColors.White,
AxislineColor = OxyColors.White,
TextColor = OxyColors.White,
TicklineColor = OxyColors.White,
StringFormat = "0.###",
});

SpectralAEPlotModel.Series.Add(new LineSeries
{
Title = "AE Data",
Color = OxyColors.White,
MarkerFill = OxyColors.White,
MarkerType = MarkerType.None,
LineStyle = LineStyle.Solid,
StrokeThickness = 2,
});
// ====================== Commands ======================
ScanCommand = new RelayCommand(o => ExecuteScan());
PauseCommand = new RelayCommand(o => ExecutePause());
SaveSpectrumCommand = new RelayCommand(o => ExecuteSaveSpectrum());
SavePngCommand = new RelayCommand(o => ExecuteSavePng());
SettingsCommand = new RelayCommand(o => ExecuteSettings());
LockCommand = new RelayCommand(o => OnLockChanged(0,0));
GoBackCommand = new RelayCommand(o => OnGoBackChanged());
}

private void MyPlotModel_MouseDown(object sender, OxyMouseDownEventArgs ex)
{
//mouseWavelengthClick = true;
OxyPlot.ElementCollection axisList = SpectralPlotModel.Axes;

Axis xAxis = axisList.FirstOrDefault(ax => ax.Position == AxisPosition.Bottom);
Axis yAxis = axisList.FirstOrDefault(ax => ax.Position == AxisPosition.Left);

NearestPoint = OxyPlot.Axes.Axis.InverseTransform(ex.Position, xAxis, yAxis);
//Debug.Print("Nearest Point: " + NearestPoint);
}

public async void OnLockChanged(int scanWindow, int intesityThreshold)
{
//Debug.Print("Wavelength Index: "+waveLengthIndex);
//Debug.Print($"Points: {NearestPoint}, scanWindowSeconds: {scanWindow},Threshold: {intesityThreshold}");
Debug.Print("Lock ..!");
Debug.Print("IsSpectralPlotVisible: "+ IsSpectralPlotVisible);
Debug.Print("IsSpectralAEPlotVisible: " + IsSpectralAEPlotVisible);
//IsSpectralPlotVisible = Visibility.Collapsed;
//IsSpectralAEPlotVisible = Visibility.Visible;
Debug.Print("IsSpectralPlotVisible: " + IsSpectralPlotVisible);
Debug.Print("IsSpectralAEPlotVisible: " + IsSpectralAEPlotVisible);
await AEHTTP.SendAEValues(new DataPoint(1552,0.4), scanWindow, intesityThreshold);
await UpdateAEPlotAsync(IP, 4004);
}

public async void OnGoBackChanged()
{
Debug.Print("Go Back ..!");
Debug.Print("IsSpectralPlotVisible: " + IsSpectralPlotVisible);
Debug.Print("IsSpectralAEPlotVisible: " + IsSpectralAEPlotVisible);
//IsSpectralPlotVisible = Visibility.Visible;
//IsSpectralAEPlotVisible = Visibility.Collapsed;
Debug.Print("IsSpectralPlotVisible: " + IsSpectralPlotVisible);
Debug.Print("IsSpectralAEPlotVisible: " + IsSpectralAEPlotVisible);
}

// ====================== Getters Setters ======================
// ====================== Commands ======================
public ICommand ScanCommand { get; }
public ICommand PauseCommand { get; }
public ICommand SaveSpectrumCommand { get; }
public ICommand SavePngCommand { get; }
public ICommand SettingsCommand { get; }
public ICommand LockCommand { get; }
public ICommand GoBackCommand { get; }
// ====================== Plotters ======================
public PlotModel SpectralPlotModel { get; set; }
public PlotModel SpectralAEPlotModel { get; set; }
// ====================== About Nearest Point Visibility ======================
public DataPoint NearestPoint
{
get
{
Debug.Print($"Entered Get {_nearestPoint}!!!");
return _nearestPoint;
}
set
{
Debug.Print($"Entered Set {value}!!!");
_nearestPoint = value;
OnPropertyChanged();
//OnPropertyChanged(nameof(NearestPoint));
}
}
// ====================== About Plot Visibility ======================
public Visibility IsSpectralPlotVisible { get; set; }
public Visibility IsSpectralAEPlotVisible { get; set; }

//private Visibility _isSpectralPlotVisible = Visibility.Visible;
//private Visibility _isSpectralAEPlotVisible = Visibility.Collapsed;
//public Visibility IsSpectralPlotVisible
//{
// get => _isSpectralPlotVisible;
// set
// {
// _isSpectralPlotVisible = value;
// OnPropertyChanged();
// }
//}
//public Visibility IsSpectralAEPlotVisible
//{
// get => _isSpectralAEPlotVisible;
// set
// {
// _isSpectralAEPlotVisible = value;
// OnPropertyChanged();
// }
//}


namespace InteWPF.ViewModel.Screens
{
public class AEViewModel : ObservableObject
{
// Variables
private PlotViewModel _plotViewModel { get; set; }

private bool _isLocked;
private int _scanWindow;
private int _intesityThreshold;

private Visibility _goBackButtonVisibility = Visibility.Collapsed;
private Visibility _lockButtonVisibility = Visibility.Visible;
public Visibility GoBackButtonVisibility
{
get => _goBackButtonVisibility;
set
{
_goBackButtonVisibility = value;
OnPropertyChanged();
}
}
public Visibility LockButtonVisibility
{
get => _lockButtonVisibility;
set
{
_lockButtonVisibility = value;
OnPropertyChanged();
}
}

public AEViewModel ()
{
_plotViewModel = new PlotViewModel();
LockCommand = new RelayCommand(ExecuteLockCommand);
GoBackCommand = new RelayCommand(ExecuteGoBackCommand);
}

public int ScanWindow
{
get => _scanWindow;
set
{
if (_scanWindow != value)
{
_scanWindow = value;
OnPropertyChanged();
}
}
}
public int IntesityThreshold
{
get => _intesityThreshold;
set
{
if (_intesityThreshold != value)
{
_intesityThreshold = value;
OnPropertyChanged();
}
}
}

//ICommand
public ICommand LockCommand { get; }
public ICommand GoBackCommand { get; }
private void ExecuteLockCommand(object parameter)
{
_plotViewModel.OnLockChanged(_scanWindow, _intesityThreshold);
_plotViewModel.IsSpectralPlotVisible = Visibility.Collapsed;
_plotViewModel.IsSpectralAEPlotVisible = Visibility.Visible;
GoBackButtonVisibility = Visibility.Visible;
LockButtonVisibility = Visibility.Collapsed;
}
private void ExecuteGoBackCommand(object parameter)
{
_plotViewModel.OnGoBackChanged();
_plotViewModel.IsSpectralPlotVisible = Visibility.Visible;
_plotViewModel.IsSpectralAEPlotVisible = Visibility.Collapsed;
GoBackButtonVisibility = Visibility.Collapsed;
LockButtonVisibility = Visibility.Visible;
}
}
}

Я не могу скрыть — сверните мой второй график, я хочу, чтобы, когда пользователь нажимает кнопку блокировки, чтобы скрыть первый график и показать второй, и если пользователь нажмет кнопку «Назад», чтобы сделать это наоборот.
Я думаю, что это проблема с моей архитектурой MVVM или что-то не так с асинхронностью? Потому что, когда я также пытаюсь передать NearestPoint с помощью функции MyPlotModel_MouseDown, я не могу получить значение для функции OnLockChanged, чтобы использовать ее.
Любая помощь будет оценена по достоинству. Спасибо!
Изменить:
Вот как мои файлы xaml.cs вызывают мои файлы модели представления:
namespace InteWPF.View.Components

{
public partial class Plot : UserControl
{
public Plot()
{
InitializeComponent();
DataContext = new PlotViewModel();
}
}
}


namespace Inte.View.Screens
{
public partial class AE : UserControl
{
public AE()
{
InitializeComponent();
DataContext = new AEViewModel();
}

}
}

Основное:
namespace InteWPF.ViewModel
{

class MainViewModel : ObservableObject
{
// Relay Commands
public RelayCommand HCommand { get; set; }
public RelayCommand AECommand { get; set; }

// ViewModels
public HomeViewModel Home { get; set; }
public AEViewModel AcousticEmission { get; set; }

private object _currentView;
public object CurrentView
{
get { return _currentView; }
set
{
if (_currentView != value)
{
_currentView = value;
OnPropertyChanged();
}
}
}

public MainViewModel()
{
//Import the Screens
Home = new HomeViewModel {};
AcousticEmission = new AEViewModel {};

//By Default
CurrentView = Home;
//Commands
HCommand = new RelayCommand((o) =>
{
CurrentView = Home;
Application.Current.MainWindow.Content = new Home {};
});

AECommand = new RelayCommand((o) =>
{
CurrentView = AcousticEmission;
Application.Current.MainWindow.Content = new AcousticEmission {};
});

}
}
}


Я также вижу, как меняются мои значения, но график не сворачивается и не появляется:
Lock ..!
IsSpectralPlotVisible: Visible
IsSpectralAEPlotVisible: Collapsed
IsSpectralPlotVisible: Collapsed
IsSpectralAEPlotVisible: Visible
Go Back ..!
IsSpectralPlotVisible: Collapsed
IsSpectralAEPlotVisible: Visible
IsSpectralPlotVisible: Visible
IsSpectralAEPlotVisible: Collapsed


Подробнее здесь: https://stackoverflow.com/questions/790 ... iewmodel-u
Реклама
Ответить Пред. темаСлед. тема

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

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

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

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

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

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