Prism для обновления Viewmodel из модели
Я думаю, что задаю свой вопрос неправильно и из-за этого у меня какой-то плохой код. То, что я хочу сделать, это иметь больше Model-Controller(?)-ViewModel-View, где я в контроллере могу иметь код, который используется в нескольких ViewModels, поэтому мне не нужно писать его более одного раза. Часть, в которой я не могу понять, - как обновить ViewModel, находясь в цикле в классе контроллера. Контроллер имеет счетчик циклов, который я хочу использовать для обновления параметра в ViewModel, но он не обновляется, пока я не вернусь к ViewModel.
Я пытаюсь выяснить, как обновить Viewmodel из модели, используя Prism. Возможно, я ошибаюсь, но я подумал, что могу сделать свой класс связываемой базой, а затем автоматически обновлять мою модель представления при ее изменении по сравнению с использованием INotifyPropertyChanged.
У меня есть метод, который просматривает некоторые каталоги и отслеживает некоторые файлы. Я хотел бы, чтобы цикл обновлял поле, которое обновляет модель представления в реальном времени, поскольку я использую BindableBase. Я считаю, что я должен иметь возможность использовать это для уведомления ViewModel об обновлениях модели. Прямо сейчас код не обновляет ViewModel автоматически, поскольку я немного растерялся относительно того, как выполнить эту задачу.
ViewModel
public class P4LabelBatteryViewModel : BindableBase
{
private P4LabelBatteryModel p4LabelBatteryModel = new P4LabelBatteryModel();
private ScriptsToTagModel scriptsToTagModel = new ScriptsToTagModel();
private P4LabelBattery.Models.BatteryLocation batteryLocation = new BatteryLocation();
public P4LabelBatteryViewModel()
{
P4LabelBattery.Models.BatteryLocation p4LabelBattery = new BatteryLocation();
// FilesProcessedBlck = p4LabelBattery.TestItem;
this.GetBatteryBtn = new DelegateCommand(chooseFile, canChooseFile);
this.NewLabelBtn = new DelegateCommand(chooseNewLabel, canNewLabel).ObservesProperty(() => NewLabel);
}
private string _batteryLocation = "Enter Location Here";
public string BatteryLocation
{
get
{
return _batteryLocation;
}
set
{
SetProperty(ref _batteryLocation, value);
}
}
public ICommand GetBatteryBtn
{
get;
set;
}
private void chooseFile()
{
BatteriesToLoad = p4LabelBatteryModel.GetBatteryFileName();
var b = BatteriesToLoad.Count;
if (b != 0)
{
ScriptCollection = scriptsToTagModel.ReadInScrpts(BatteriesToLoad[b-1].BatteryLocationAdd);
BatteryLocation = BatteriesToLoad[b - 1].BatteryLocationAdd;
}
}
private bool canChooseFile()
{
if (BatteriesToLoad != null)
{
return true;
}
else
{
return true;
}
}
public ICommand NewLabelBtn
{
get;
set;
}
private void chooseNewLabel()
{
if (ScriptCollection.Count > 0)
{
ScriptCollection = P4LabelBatteryModel.LocatePNGModel(NewLabel, ScriptCollection, batteryLocation);
// FilesProcessedBlck = ScriptCollection.Count;
ScriptCollection = P4LabelBatteryModel.TagsFilesModel(NewLabel, ScriptCollection, FilesProcessedBlck);
}
}
private bool canNewLabel()
{
if (NewLabel == null || NewLabel == "Enter Label Here" || NewLabel == "")
{
return false;
}
else
{
return true;
}
}
private string _newLabel;
public string NewLabel
{
get
{
return _newLabel;
}
set
{
SetProperty(ref _newLabel, value);
canNewLabel();
}
}
private int _filesProcessedBlck;
public int FilesProcessedBlck
{
get
{
return _filesProcessedBlck;
}
set
{
SetProperty(ref _filesProcessedBlck, batteryLocation.TestItem);
}
}
private ObservableCollection<ScriptModel> _scriptCollection = new ObservableCollection<ScriptModel>();
public ObservableCollection<ScriptModel> ScriptCollection
{
get
{
return _scriptCollection;
}
set
{
SetProperty(ref _scriptCollection, value);
}
}
private ObservableCollection<BatteryLocation> _batteriesToLoad = new ObservableCollection<BatteryLocation>();
public ObservableCollection<BatteryLocation> BatteriesToLoad
{
get
{
return _batteriesToLoad;
}
set
{
SetProperty(ref _batteriesToLoad, value);
}
}
}
Модель:
class P4LabelBatteryModel : BindableBase
{
private string _MasterFile2 = "0";
private ObservableCollection<BatteryLocation> batteryLocationColl = new ObservableCollection<BatteryLocation>();
public ObservableCollection<BatteryLocation> GetBatteryFileName()
{
if (_MasterFile2 != "1")
{
Microsoft.Win32.OpenFileDialog _MasterFileDialog = new Microsoft.Win32.OpenFileDialog();
_MasterFileDialog.DefaultExt = "*.*";
// _MasterFileDialog.Filter = "All Files (*.scr; *.SCR) | *.scr; *.SR";
Nullable<bool> result = _MasterFileDialog.ShowDialog();
BatteryLocation batteryLocation = new BatteryLocation();
batteryLocation.BatteryLocationAdd = _MasterFileDialog.FileName;
if (result == true && !batteryLocationColl.Contains(batteryLocation))
{
batteryLocation.BatteryLocationAdd = _MasterFileDialog.FileName;
batteryLocationColl.Add(batteryLocation);
}
}
return batteryLocationColl;
}
public static ObservableCollection<ScriptModel> LocatePNGModel(string NewLabel, ObservableCollection<ScriptModel> observableCollection, BatteryLocation FilesProcessedBlck)
{
string newLabel = NewLabel;
var scriptsToTagColl = observableCollection;
string[] files = null;
FilesProcessedBlck.TestItem = 40;
// ObservableCollection<ScriptModel> newCollection = new ObservableCollection<ScriptModel>();
int CollCount = scriptsToTagColl.Count;
for (int i = 0; i < CollCount; i++)
{
//Check for 4th occurance of \ to search for .png files.
// Modify path for non-standard script locations.
if (!scriptsToTagColl[i].ScriptNameAdd.Contains("Scripts"))
{
int j = 0;
int m = 0;
for (int k = 0; k <= 4 && k < scriptsToTagColl[i].ScriptNameAdd.Count(); k++)
{
if (j != -1)
{
if ((j = scriptsToTagColl[i].ScriptNameAdd.IndexOf(@"\", j)) != -1 && k == 4)
{
//add directory search for .png
string teststring = scriptsToTagColl[i].ScriptNameAdd;
int testint = teststring.Count();
int ttt = testint;
string _edtdString = teststring.Remove(j, testint - j);
try
{
foreach (string d in Directory.GetDirectories(_edtdString))
{
try
{
files = Directory.GetFiles(d, "*.png", SearchOption.AllDirectories);
foreach (string file1 in files)
{
ScriptModel _scriptModel = new ScriptModel();
_scriptModel.ScriptNameAdd = file1;
scriptsToTagColl.Add(_scriptModel);
// newCollection.Add(_scriptModel);
}
}
catch (Exception e)
{
//don't care right now.
//files = null;
//testscript2 = testscript.Insert(index + @"Scripts\".Length, @"Results\");
//trimmed = testscript.TrimEnd('.', 's', 'c', 'r');
//trimmed += @"\mill\Snapshots\BCM";
int stophere = 2;
}
}
}
catch (Exception e)
{
//don't care right now
int stophere2 = 2;
}
break;
}
j++;
}
}
}
//End of check
else
{
string testscript = scriptsToTagColl[i].ScriptNameAdd;
int index = testscript.IndexOf(@"Scripts\");
files = null;
string testscript2 = testscript.Insert(index + @"Scripts\".Length, @"Results\");
string trimmed = testscript2.TrimEnd('.', 's', 'c', 'r');
trimmed += @"\mill\Snapshots\BCM";
if (Directory.Exists(@trimmed))
{
try
{
files = Directory.GetFiles(@trimmed, "*.*");
foreach (string file1 in files)
{
ScriptModel _scriptModel = new ScriptModel();
_scriptModel.ScriptNameAdd = file1;
// newCollection.Add(_scriptModel);
scriptsToTagColl.Add(_scriptModel);
}
}
catch (Exception e)
{
//don't care right now.
files = null;
testscript2 = testscript.Insert(index + @"Scripts\".Length, @"Results\");
trimmed = testscript.TrimEnd('.', 's', 'c', 'r');
trimmed += @"\mill\Snapshots\BCM";
}
}
}
}
return scriptsToTagColl;
}
public static ObservableCollection<ScriptModel> TagsFilesModel(string NewLabel, IList<ScriptModel> observableCollection, int FileCount)
{
string newLabel = NewLabel;
var scriptsToTagColl = observableCollection;
int fileCount = FileCount;
var _p4LabelBatteryViewModel = new P4LabelBatteryViewModel();
//This will generate an IPC when returned
ObservableCollection<ScriptModel> newCollection = new ObservableCollection<ScriptModel>();
int CollCount = scriptsToTagColl.Count;
for (int i = 0; i < scriptsToTagColl.Count; i++)
{
var stringToTest = scriptsToTagColl[i].ScriptNameAdd;
string tempString = @" """;
// if (stringToTest.Contains(" "))
// {
tempString = tempString + stringToTest;
stringToTest = " " + tempString;
// }
System.Diagnostics.Process proc = new System.Diagnostics.Process();
StringBuilder q = new StringBuilder();
string FileName1 = @"c:\windows\system32\cmd.exe";
string Arguments1 = string.Format("@ /c p4 tag -l {0} {1}", newLabel, stringToTest);
proc.StartInfo = new ProcessStartInfo(FileName1, Arguments1);
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
q.Append(proc.StandardError.ReadToEnd());
//while (!proc.HasExited)
//{
// q.Append(proc.StandardOutput.ReadToEnd());
//}
string r = q.ToString();
if ( ! r.Contains("no such file(s)"))
{
scriptsToTagColl[i].BackGround = new SolidColorBrush(Colors.LightGreen);
}
newCollection.Add(scriptsToTagColl[i]);
}
return newCollection;
}
}
public class BatteryLocation :BindableBase
{
private string _batteryLocationAdd;
public string BatteryLocationAdd
{
get { return _batteryLocationAdd; }
set { _batteryLocationAdd = value; }
}
private SolidColorBrush _backGround;
public SolidColorBrush BackGround
{
get { return _backGround; }
set { _backGround = value; }
}
private int _testItem = 100;
public int TestItem
{
get {return _testItem;}
set { _testItem = value; }
}
}
}