wpf UI not updating on data context change - c#

I am developing and wpf app and in which I need to update data on basis of click on button. I tried to update in code behind but it did not work so I used datacontext but still no use. I saw various solutions and have used mode=TwoWay, UpdateSourceTrigger but it does not work.
<Grid DataContext="{Binding Dashboard, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
//Content
</Grid>
In cs file
public ViewModels.DashboardVM _DashVM = new ViewModels.DashboardVM();
async private void DashboardPage_Loaded(object sender, RoutedEventArgs e)
{
try
{
await _DashVM.GetDashboardData();
this.DataContext = _DashVM;
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex.Message);
}
}
and changing data context here
async private void StoresList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
var item = (sender as ListView).SelectedItem as Models.StoresLM;
if(item!=null)
{
Properties.Settings.Default.StoreId = item.id;
Properties.Settings.Default.Save();
await _DashVM.GetDashboardData();
this.DataContext = _DashVM;
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex.Message);
}
}
my View Model is
public class DashboardVM : INotifyPropertyChanged
{
private Models.DashboardM _dashboard;
public Models.DashboardM Dashboard
{
get { return _dashboard; }
set { _dashboard = value; RaisePropertyChanged("Dashboard"); }
}
private void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public static event EventHandler<Boolean> IsLoading = delegate { };
async public Task<Boolean> GetDashboardData()
{
try
{
if (InternetTools.IsNetworkConnected())
{
IsLoading(this, true);
var storeId = Convert.ToString(Properties.Settings.Default.StoreId);
var Response = await new WebServiceUtility().PostRequest(string.Format(StringUtility.DashboardApi, Convert.ToString(Properties.Settings.Default.StoreId)), new[] { new KeyValuePair<string, string>("api_key", "dbjh") });
if (Response.IsSuccessStatusCode)
{
var DashboardData = await Response.Content.ReadAsStringAsync();
var jsonObject = Newtonsoft.Json.Linq.JObject.Parse(DashboardData);
if (Convert.ToString(jsonObject["success"]).IndexOf("True", StringComparison.OrdinalIgnoreCase) >= 0)
{
var DashObject = jsonObject.ToObject<Models.DashboardM>();
Properties.Settings.Default.Currency = DashObject.data.store.currency.StartsWith("&") ? System.Net.WebUtility.HtmlDecode(DashObject.data.store.currency) : System.Text.RegularExpressions.Regex.Unescape(DashObject.data.store.currency);
DashObject.data.store.currency = StringUtility.Currency;
Properties.Settings.Default.Save();
Dashboard = null;
Dashboard = DashObject;
}
}
}
else
NotificationUtility.ShowErrorMessage(NotificationUtility.MsgType.InternetError);
}
catch
{
}
IsLoading(this, false);
return true;
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
}
Can anybody help?

I was able to resolve the problem by editing the code. It was not getting notified due to reassigning of object. I don't know the reason but I just changed this code
async private void StoresList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
var item = (sender as ListView).SelectedItem as Models.StoresLM;
if(item!=null)
{
Properties.Settings.Default.StoreId = item.id;
Properties.Settings.Default.Save();
await _DashVM.GetDashboardData();
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex.Message);
}
}
Hope it helps somebody like me.

Related

Xamarin Listview only adding 1 item my List has 2 items on it

I have a listview and a method to get the items via Bluethoot conection to a Radio device, when the method ends i have two items in my itemsList but only one is showing on my ListView, also the item is not visible until i click the screen for some reason.
Any help on how to present my two items at once inside of the ListView?
I think it has something to do with the way im handling the EventRead and EventStopped, maybe its not getting any time to update
public partial class ReadAnyPage : ContentPage
{
IRadioPlatform _platform;
DropdownTypes dropdownTypes;
Task<List<ChoiceConnectEndpoint>> _readAnyComplete;
public event EventHandler OnStopped;
public event EventHandler<Itron.Mobile.Radio.Communication.SRead.HandledEventArgs<ChoiceConnectEndpoint>> readEndpoints;
private List<JsonDict> itemsList = new List<JsonDict>();
string bleName, blePort;
public ReadAnyPage()
{
InitializeComponent();
BindingContext = this; //Added this
_platform = DependencyService.Get<IRadioPlatform>();
dropdownTypes = new DropdownTypes();
bleName = Preferences.Get("ble_name", "");
blePort = Preferences.Get("ble_port", "");
CancellationTokenSource tokenSource = new CancellationTokenSource();
CancellationToken token = tokenSource.Token;
listView.ItemsSource = itemsList;
ReadAnyNear(tokenSource, token);
}
private void ReadAnyNear(CancellationTokenSource tokenSource, CancellationToken token)
{
var loading = UserDialogs.Instance.Loading("Reading Endpoints...", onCancel: tokenSource.Cancel, "\n\n" + Resx.Resources.Cancel, true, MaskType.Black);
try
{
// Set new IMR
IMRRadioService imrRadioService = new IMRRadioService(_platform);
imrRadioService.Name = bleName;
imrRadioService.Port = blePort;string
readEndpoints += EventRead;
OnStopped += EventStopped;
_readAnyComplete = imrRadioService.ReadAny(token, readEndpoints, OnStopped);
}
catch (Exception ex)
{
DisplayAlert("Error", dropdownTypes.OnConvertErrorEX(ex.Message), "ok", "cancel");
}
loading.Hide();
}
private void EventRead(object sender, EventArgs e)
{
Console.WriteLine("READ READ");
try
{
Itron.Mobile.Radio.Communication.SRead.HandledEventArgs<ChoiceConnectEndpoint> item = (Itron.Mobile.Radio.Communication.SRead.HandledEventArgs<ChoiceConnectEndpoint>)e;
JsonDict jsonDict = new JsonDict();
jsonDict.RadioNumber = item.Data.EndpointId.ToString();
jsonDict.MeterType = item.Data.MarketType.ToString();
jsonDict.Read = ((Endpoint100G)item.Data).Reading.Read.ToString();
jsonDict.ModuleType = item.Data.EndpointTypeName;
jsonDict.ServiceType = item.Data.MarketType.ToString();
itemsList.Add(jsonDict);
Console.WriteLine("Count:" + itemsList.Count);
listView.ItemsSource = itemsList;
}
catch (Exception ex)
{
Console.WriteLine("Error:" + ex.Message);
}
}
private void EventStopped(object sender, EventArgs e)
{
Console.WriteLine("STOPPED");
}
private async void ListView_ItemTapped(object sender, ItemTappedEventArgs e)
{
}
private void ListView_Refreshing(object sender, EventArgs e)
{
OnRefreshDevicesList();
}
private void OnRefreshDevicesList()
{
listView.EndRefresh();
}
}
Solved thanks to #Jason from this
private List<JsonDict> itemsList = new List<JsonDict>();
To this
private ObservableCollection<JsonDict> itemsList = new ObservableCollection<JsonDict>();

Moving code behind xaml.cs to ViewModel in xamarin

I have coded my behind code logic in xaml.cs file and now i want to move my code from code behind to ViewModel. How can this be done apart from code refactoring.
I am new to xamarin
Here is my Code behind
namespace _somename
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class CareingtonFeeSchedule : ContentPage
{
private OneDentalFeeScheduleService oneDentalFeeScheduleService;
private ObservableCollection<ProviderSearchViewModel> _allGroups;
private ObservableCollection<ProviderSearchViewModel> _expandedGroups;
protected ObservableCollection<Grouping<string, FeeScheduleItem>> feeScheduleGroups;
protected ObservableCollection<FeeScheduleItem> feeScheduleItems;
private readonly AppViewModel AppViewModelInstance;
private Plugin.Geolocator.Abstractions.Position currentPosition;
private FeeScheduleModel feeScheduleDataResult;
public CareingtonFeeSchedule(AppViewModel appViewModel)
{
InitializeComponent();
AppViewModelInstance = appViewModel;
BindingContext = AppViewModelInstance;
AppViewModelInstance.IsActivityLoading = true;
LoadFeeeSchedule();
}
private void HeaderTapped(object sender, EventArgs args)
{
int selectedIndex = _expandedGroups.IndexOf(
((ProviderSearchViewModel)((Button)sender).CommandParameter));
_allGroups[selectedIndex].Expanded = !_allGroups[selectedIndex].Expanded;
UpdateListContent();
}
async Task OnHomeFeeScheduleTapped_TappedAsync(object sender, EventArgs args)
{
await Navigation.PushAsync(new AccLandPage(AppViewModelInstance));
}
private void ProviderBar_TextChanged(object sender, TextChangedEventArgs e)
{
var keyword = ProviderSearchBar.Text;
GroupedView.ItemsSource =
_expandedGroups.Where(s =>
s.Title.ToLower().Contains(keyword.ToLower()));
}
private void UpdateListContent()
{
_expandedGroups = new ObservableCollection<ProviderSearchViewModel>();
foreach (ProviderSearchViewModel group in _allGroups)
{
ProviderSearchViewModel newGroup = new ProviderSearchViewModel(group.Title, group.ShortName, group.Expanded);
if (group.Expanded)
{
foreach (Plan plan in group)
{
newGroup.Add(plan);
}
}
_expandedGroups.Add(newGroup);
}
GroupedView.ItemsSource = _expandedGroups;
}
public FeeScheduleModel FeeScheduleDataResult
{
protected set
{
feeScheduleDataResult = value;
OnPropertyChanged(nameof(FeeScheduleDataResult));
}
get => feeScheduleDataResult;
}
protected int feeScheduleCount;
public int FeeScheduleCount => feeScheduleCount;
private async Task<bool> LoadFeeeSchedule()
{
try
{
if (oneDentalFeeScheduleService == null)
{
oneDentalFeeScheduleService = new OneDentalFeeScheduleService("1dental.com");
}
var feeSchedRes = await oneDentalFeeScheduleService.GetFeeScheduleAsync(AppViewModelInstance.ZipCode, string.Empty, CancellationToken.None);
if (feeSchedRes?.Schedule?.Count > 0)
{
ConvertFeeScheuleDict(feeSchedRes.Schedule);
}
else FeeScheduleDataResult = null;
return true;
}
catch (Exception eX)
{
with the fee schedule lookup: \n{eX.Message}", "OK");
return false;
}
finally
{
AppViewModelInstance.IsActivityLoading = false;
actInd.IsRunning = false;
}
}
private void ConvertFeeScheuleDict(Dictionary<string, List<FeeScheduleItem>> feesche)
{
ObservableCollection<ProviderSearchViewModel> list = new ObservableCollection<ProviderSearchViewModel>();
ProviderSearchViewModel psm = null;
foreach (var item in feesche)
{
psm = new ProviderSearchViewModel(item.Key, "");
foreach (var valitem in item.Value)
{
Plan p = new Plan();
p.Code = valitem.Code;
p.CostDisplay = valitem.CostDisplay;
p.Description = valitem.ProcedureSecondary;
p.Name = valitem.Procedure;
psm.Add(p);
}
list.Add(psm);
}
_allGroups = list;
UpdateListContent();
}
private async void GetZipCode()
{
try
{
if (AppViewModelInstance.UserPosition == null)
{
try
{
var hasPermission = await Utils.CheckPermissions(Permission.Location);
if (!hasPermission)
{
await Navigation.PushAsync(new MainScreen());
return;
}
}
catch (Exception ex)
{
Debug.WriteLine($"Exception occurred while looking permission during Appearing event: {ex}");
}
var locator = CrossGeolocator.Current;
currentPosition = await locator.GetPositionAsync(new TimeSpan(0, 0, 0, 10, 0));
var addressList = await locator.GetAddressesForPositionAsync(currentPosition, null);
AppViewModelInstance.UserPosition = currentPosition;
foreach (var item in addressList)
{
AppViewModelInstance.ZipCode = item.PostalCode;
ZipCodeEntry.Text = item.PostalCode;
break;
}
}
else
{
var locator = CrossGeolocator.Current;
currentPosition = AppViewModelInstance.UserPosition;
var addressList = await locator.GetAddressesForPositionAsync(currentPosition, null);
foreach (var item in addressList)
{
AppViewModelInstance.ZipCode = item.PostalCode;
ZipCodeEntry.Text = item.PostalCode;
break;
}
}
LoadFeeeSchedule();
}
catch (Exception ex)
{
Debug.WriteLine($"Exception occurred while looking up location during Appearing event: {ex}");
}
}
private void ZipCodeEntry_Complete(object sender, EventArgs e)
{
if (sender != null)
{
AppViewModelInstance.ZipCode = ((Entry)sender).Text;
}
}
private void ZipCodeEntry_Changed(object sender, EventArgs e)
{
if (sender != null)
{
string _text = ((Entry)sender).Text; //Get Current Text
if (_text.Length > 5) //If it is more than your character restriction
{
_text = _text.Remove(_text.Length - 1); // Remove Last character
ZipCodeEntry.Text = _text; //Set the Old value
}
if (_text.Length == 5)
{
AppViewModelInstance.ZipCode = _text;
LoadFeeeSchedule();
}
}
}
public bool CanRefreshExecute(string tempVal = null)
{
if (AppViewModelInstance.IsRefreshing) return false;
var valToCheck = tempVal ?? AppViewModelInstance.ZipCode;
if (string.IsNullOrEmpty(valToCheck) || string.IsNullOrWhiteSpace(valToCheck)) return false;
bool isDigitString = true;
foreach (var c in valToCheck)
{
if (char.IsDigit(c)) continue;
isDigitString = false;
}
if (isDigitString) AppViewModelInstance.ZipCode = valToCheck;
return isDigitString;
}
private void GroupedView_ItemTapped(object sender, ItemTappedEventArgs e)
{
}
}
}
just export your code to the view model and set the view model as binding context of the Page. For example in the constructor:
//In the code behind
PageViewModel viewModel;
public Page()
{
this.BindingContext = viewModel = new PageViewModel();
//...
}
The ViewModel should implement INotifyPropertyChanged.
(Functions which are triggered by events have to stay in the code behind and access the view model through the ViewModel Property)

Zebra Android Scanner does not re-initialize in Activity

I am building a Xamarin.Android application for a Zebra TC-70 Android device. My main activity runs the scanner just fine the first time through. It gets the data from the scanner and then passes data to another activity just fine. If I cancel the new activity or complete my work and return to the first activity, the scanner does not re-initialize. Here is my code:
[Activity(Label = "MyApp", MainLauncher = true, Icon = "#mipmap/icon",
ScreenOrientation = ScreenOrientation.Portrait)]
public class MainActivity : AppCompatActivity, EMDKManager.IEMDKListener
{
//EMDK
private BarcodeManager _barcodeManager;
private EMDKManager _emdkManager;
private EditText _scanBarcodeEditText;
private Scanner _scanner;
void EMDKManager.IEMDKListener.OnClosed()
{
if(_emdkManager != null)
{
_emdkManager.Release();
_emdkManager = null;
}
}
void EMDKManager.IEMDKListener.OnOpened(EMDKManager p0)
{
_emdkManager = p0;
InitScanner();
}
protected override void OnResume()
{
base.OnResume();
var intent = new Intent(this, typeof(FpmsDataService));
BindService(intent, _dataServiceConnection, Bind.AutoCreate);
_scanBarcodeEditText.Text = string.Empty;
InitScanner();
}
protected override void OnPause()
{
base.OnPause();
UnbindService(_dataServiceConnection);
DeinitScanner();
if (_emdkManager != null)
{
_emdkManager.Release();
_emdkManager = null;
}
}
protected override void OnDestroy()
{
base.OnDestroy();
DeinitScanner();
if(_emdkManager != null)
{
_emdkManager.Release();
_emdkManager = null;
}
Log.Information("Destroyed FirePMS MainActivity");
Log.CloseAndFlush();
}
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Window.SetFlags(WindowManagerFlags.KeepScreenOn, WindowManagerFlags.KeepScreenOn);
SetContentView(Resource.Layout.Main);
_scanBarcodeEditText = FindViewById<EditText>(Resource.Id.MaintenanceScanBarcode_EditText);
//Initialize Scanner
var results = EMDKManager.GetEMDKManager(Application.Context, this);
}
private void InitScanner()
{
if(_emdkManager != null)
{
if(_barcodeManager == null)
{
try
{
//Get the feature object such as BarcodeManager object for accessing the feature.
_barcodeManager = (BarcodeManager)_emdkManager.GetInstance(EMDKManager.FEATURE_TYPE.Barcode);
_scanner = _barcodeManager.GetDevice(BarcodeManager.DeviceIdentifier.Default);
if (_scanner != null)
{
//Attach the Data Event handler to get the data callbacks.
_scanner.Data += Scanner_Data;
_scanner.Status += Scanner_Status;
_scanner.Enable();
}
else
{
Log.Error("Failed to enable scanner");
}
}
catch (ScannerException e)
{
Log.Error(e.Message);
}
catch (Exception ex)
{
Log.Error(ex.Message);
}
}
}
}
private void Scanner_Status(object sender, Scanner.StatusEventArgs e)
{
var state = e.P0.State;
if(state == StatusData.ScannerStates.Idle)
{
try
{
if (_scanner.IsEnabled &&
!_scanner.IsReadPending)
{
SetScannerConfig();
_scanner.Read();
}
}
catch (ScannerException e1)
{
Log.Error(e1.Message);
}
}
}
private void DeinitScanner()
{
if(_emdkManager != null)
{
if(_scanner != null)
{
try
{
_scanner.CancelRead();
_scanner.Disable();
_scanner.Data -= Scanner_Data;
_scanner.Status -= Scanner_Status;
_scanner.Release();
}
catch (ScannerException e)
{
Log.Error(e.Result.Description);
}
}
}
if (_barcodeManager != null)
{
_emdkManager.Release(EMDKManager.FEATURE_TYPE.Barcode);
}
_barcodeManager = null;
_scanner = null;
}
private void SetScannerConfig()
{
var config = _scanner.GetConfig();
config.SkipOnUnsupported = ScannerConfig.SkipOnUnSupported.None;
config.ScanParams.DecodeLEDFeedback = true;
config.ReaderParams.ReaderSpecific.ImagerSpecific.PicklistEx = ScannerConfig.PicklistEx.Hardware;
config.DecoderParams.Code39.Enabled = true;
config.DecoderParams.Code128.Enabled = false;
_scanner.SetConfig(config);
}
private void Scanner_Data(object sender, Scanner.DataEventArgs e)
{
var scanDataCollection = e.P0;
if((scanDataCollection != null) && (scanDataCollection.Result == ScannerResults.Success))
{
var scanData = scanDataCollection.GetScanData();
if (scanData[0].Data == null)
{
return;
}
RunOnUiThread(() => _scanBarcodeEditText.Text = scanData[0].Data);
RunOnUiThread(ProcessScan);
}
}
private void ProcessScan()
{
if (string.IsNullOrEmpty(_scanBarcodeEditText.Text))
{
Toast.MakeText(this, "You must scan or enter a barcode to begin", ToastLength.Long).Show();
return;
}
else
{
var intent = new Intent(this, typeof(SecondActivity));
intent.PutExtra("ScannedData",_scanBarcodeEditText.Text);
StartActivity(intent)
}
}
}
Any suggestions would be greatly appreciated. As I indicated, the process works just fine the first time, it's when I return to this activity that the scanner is no longer initialized and doesn't come back.
I suspect the EMDK is not being properly released before the activity is restarted. If you take a look at the following article, though using Java the principle is the same and the advice there is to release the EMDK in onStop(). See the note about managing the EMDK instance about half way down.

Background Worker Call Method or something

I have a method/procedure which works well, however it takes ages to do its thing so I want to move it into a background worker so people can still use the app.
Here is the code. (I cut down as much as I could)
public partial class NetworkInformation : UserControl, INotifyPropertyChanged
{
public NetworkInformation()
{
InitializeComponent();
Discovery();
}
public void Discovery()
{
GetIcon Icon = new GetIcon();
BitmapImage IconOfComputer = null;
List<DiscoveredComputer> NetworkedComputers = new List<DiscoveredComputer>();
DirectoryEntry Discover = new DirectoryEntry("WinNT://Workgroup");
BitmapImage On = Icon.LoadIcon(#"/Images/Icons/ComputerOn.ico");
BitmapImage Off = Icon.LoadIcon(#"/Images/Icons/ComputerOff.ico");
foreach (DirectoryEntry Node in Discover.Children)
{
try
{
if (Node.Properties.Count > 0)
{
IconOfComputer = On;
}
}
catch
{
IconOfComputer = Off;
}
if (Node.Name != "Schema") { NetworkedComputers.Add(new DiscoveredComputer { Image = IconOfComputer, ComputerName = Node.Name, MyToolTip = "Node Type = " + Node.SchemaEntry.Name }); }
}
ListView_LocalComputers.ItemsSource = NetworkedComputers;
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string PropertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
}
}
public class DiscoveredComputer : INotifyPropertyChanged
{
private string _ComputerName;
public string ComputerName
{
get { return _ComputerName; }
set
{
_ComputerName = value;
this.NotifyPropertyChanged("ComputerName");
}
}
private BitmapImage _Image;
public BitmapImage Image {
get { return _Image; }
set
{
_Image = value;
this.NotifyPropertyChanged("Image");
}
}
private String _MyToolTip;
public String MyToolTip
{
get { return _MyToolTip; }
set
{
_MyToolTip = value;
this.NotifyPropertyChanged("ToolTip");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string PropertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
}
}
public class GetIcon
{
public BitmapImage IconStorage { get; set; }
public BitmapImage LoadIcon(String IconPath)
{
BitmapImage GeneratedIcon = new BitmapImage();
GeneratedIcon.BeginInit();
GeneratedIcon.UriSource = new Uri("pack://application:,,," + IconPath, UriKind.RelativeOrAbsolute);
GeneratedIcon.EndInit();
IconStorage = GeneratedIcon;
return GeneratedIcon;
}
}
}
This all works awesomely, somehow...
Here is the code I:developed for my background worker
public partial class MyBackgroundWorker : UserControl
{
WorkerData BGW;
public MyBackgroundWorker()
{
InitializeComponent();
BGW = new WorkerData();
#region Workers Events
BGW.ThisWorker.DoWork += new DoWorkEventHandler(Workers_DoWork);
BGW.ThisWorker.ProgressChanged += new ProgressChangedEventHandler(Workers_Progress);
BGW.ThisWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Workers_Completed);
BGW.ThisWorker.WorkerReportsProgress = true;
BGW.ThisWorker.WorkerSupportsCancellation = true;
#endregion
}
public void RibbonButton_EventClickStart(object sender, RoutedEventArgs e)
{
BGW.ThisWorker.RunWorkerAsync();
}
public void UserForm_Loaded(object sender, RoutedEventArgs e)
{
}
public void RibbonButton_EventClick(object sender, RoutedEventArgs e)
{
BGW.ThisWorker.CancelAsync();
}
public void Workers_DoWork(object sender, DoWorkEventArgs e)
{
}
public void Workers_Progress(object sender, ProgressChangedEventArgs e)
{
BGW.ThisWorkersProgress = e.ProgressPercentage;
}
public void Workers_Completed(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled) { BGW.ThisWorkersResult = "Cancelled By User"; }
else if (e.Error != null) { BGW.ThisWorkersResult = "Error Encountered: " + e.Error.Message; }
else
{
BGW.ThisWorkersResult = "Task Completed Successfully";
BGW.WorkersReturnObject = e.Result;
}
}
}
public class WorkerData
{
public BackgroundWorker ThisWorker { get; set; }
public int ThisWorkersProgress { get; set; }
public string ThisWorkersResult { get; set; }
public object WorkersReturnObject { get; set; }
public object ThisWorkersJob { get; set; }
public WorkerData()
{
ThisWorker = new BackgroundWorker();
}
}
So how do I get my background worker to run the Discovery method I have created?
You need to do your work in the DoWork event handler.
I don't know if you need a whole separate class for this. I prefer to create these as I need them, on the fly. I think you'll get yourself shoehorned, where you'll use your class in multiple places and then decide you want to do something else in Workers_Completed in certain cases, or do something different when an error occurs in certain cases, and that one class could end up being a tangled-up pain. That's just my opinion though.
Also, you have to be very careful about touching the UI thread from your BackgroundWorker. In the example below, I'm passing in your node count to the DoWork event, instead of having it possibly touch a UI component directly. I'm also passing the list to the RunWorkerCompleted event, so that you're back in the main thread when it tries to attach the list to your ListView.
var bw = new BackgroundWorker();
bw.DoWork += (s, e) =>
{
var nodePropertiesCount = (int)e.Argument;
// the guts of `Discovery` go in here
e.Result = NetworkedComputers;
};
bw.RunWorkerCompleted += (s, e) =>
{
if (e.Error != null)
{
// Task Completed Successfully
ListView_LocalComputers = (List<DiscoveredComputer>)e.Result;
}
else
{
// Error Encountered
}
};
bw.RunWorkerAsync(Node.Properties.Count);
SLaks answer is correct, but you apparently don't understand what that means. I'd suggest taking the guts of Discover() and putting them in the Workers_DoWork() method like this:
public void Workers_DoWork(object sender, DoWorkEventArgs e)
{
var backgroundWorker = sender as BackgroundWorker;
GetIcon Icon = new GetIcon();
BitmapImage IconOfComputer = null;
List<DiscoveredComputer> NetworkedComputers = new List<DiscoveredComputer>();
DirectoryEntry Discover = new DirectoryEntry("WinNT://Workgroup");
BitmapImage On = Icon.LoadIcon(#"/Images/Icons/ComputerOn.ico");
BitmapImage Off = Icon.LoadIcon(#"/Images/Icons/ComputerOff.ico");
while (!backgroundWorker.CancellationPending)
{
foreach (DirectoryEntry Node in Discover.Children)
{
try
{
if (Node.Properties.Count > 0)
{
IconOfComputer = On;
}
}
catch
{
IconOfComputer = Off;
}
if (Node.Name != "Schema") { NetworkedComputers.Add(new DiscoveredComputer { Image = IconOfComputer, ComputerName = Node.Name, MyToolTip = "Node Type = " + Node.SchemaEntry.Name }); }
}
break;
}
if(backgroundWorker.CancellationPending)
{
e.Cancel = true;
}
else
{
e.Result = NetworkedComputers;
}
}
And then modifying your Workers_Completed() like this:
public void Workers_Completed(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled) { BGW.ThisWorkersResult = "Cancelled By User"; }
else if (e.Error != null) { BGW.ThisWorkersResult = "Error Encountered: " + e.Error.Message; }
else
{
BGW.ThisWorkersResult = "Task Completed Successfully";
//BGW.WorkersReturnObject = e.Result;
//background worker can't touch UI components
ListView_LocalComputers.ItemsSource = e.Result as List<DiscoveredComputer>;
}
}
I suggest these changes, or something similar, because the background worker can't modify/access UI components (like your ListView), so it has to pass back the value to use for the ListView view its Result property. I also included a simple way of detecting cancellation; I'll leave progress reporting up to you to implement.

Binding a ListBox to a List<string>

I am trying to bind a list of strings to the contents of a list box. For some reason, I get results for bluetape list, but the contents of BluetapeList does not ever make it into the listbox. Any help would be much appreciated!
XAML:
<ListBox
Name="lbxTapeIn"
Grid.Row="1"
Grid.Column="1"
Grid.ColumnSpan="1"
Width="70"
Height="80"
SelectionChanged="TapeSelectionChanged"
ItemsSource="{Binding}"
SelectedValue="{Binding SelectedBt}"
Background="DeepSkyBlue"
Foreground="MidnightBlue"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Margin="5"/>
Code Behind:
public partial class OverrideAoiBinningWindow : Window
{
private OverrideAoiBinningWindowViewModel ovAoiBinWin;
public OverrideAoiBinningWindow()
{
InitializeComponent();
ovAoiBinWin = new OverrideAoiBinningWindowViewModel(tvwWaferList, txtFilter);
AssignDataContexts();
}
private void AssignDataContexts()
{
btnChooseWafer.DataContext = ovAoiBinWin;
btnSave.DataContext = ovAoiBinWin;
txtWafer.DataContext = ovAoiBinWin;
cbxAoiState.DataContext = ovAoiBinWin;
lbxTapeIn.DataContext = ovAoiBinWin.BluetapeList;
}
private void TapeSelectionChanged(object sender, RoutedEventArgs e)
{
if (!string.IsNullOrEmpty(ovAoiBinWin.SelectedWafer))
{
if (cbxAoiState.SelectedValue != null)
{
btnSave.IsEnabled = true;
}
}
}
private void AoiStateChanged(object sender, RoutedEventArgs e)
{
if (!string.IsNullOrEmpty(ovAoiBinWin.SelectedWafer))
{
if (lbxTapeIn.SelectedValue != null)
{
btnSave.IsEnabled = true;
}
}
}
private void Close(object sender, RoutedEventArgs e)
{
this.Close();
}
}
View Model:
public class OverrideAoiBinningWindowViewModel : ViewModelBase, ISelectWafers
{
public OverrideAoiBinningWindowViewModel(TreeView tvwWaferList, TextBox txtFilter)
{
// Set private fields
this.tvwWaferList = tvwWaferList;
this.txtFilter = txtFilter;
// Instantiate objects and initialize settings
this.InstantiateObjects();
this.SetControlSettings();
// Run the initialization thread
initThread.RunWorkerAsync();
}
public string SelectedWafer
{
get
{
return selectedWafer;
}
set
{
selectedWafer = value;
OnPropertyChanged("SelectedWafer");
}
}
public string SelectedBt
{
get
{
return selectedBt;
}
set
{
selectedBt = value;
OnPropertyChanged("SelectedBt");
}
}
public string SelectedAoiState
{
get
{
return selectedAoiState;
}
set
{
selectedAoiState = value;
OnPropertyChanged("SelectedAoiState");
}
}
public List<string> AOIStateList
{
get
{
return aoiStateList;
}
set
{
aoiStateList = value;
OnPropertyChanged("AOIStateList");
}
}
public List<string> BluetapeList
{
get
{
return bluetapeList;
}
set
{
bluetapeList = value;
OnPropertyChanged("BluetapeList");
}
}
public ICommand SelectWaferCommand
{
get
{
if (selectWaferCommand == null)
{
selectWaferCommand = new DelegateCommand(SelectWafer);
}
return selectWaferCommand;
}
}
public ICommand SaveAoiStateCommand
{
get
{
if (saveAoiStateCommand == null)
{
saveAoiStateCommand = new DelegateCommand(SaveAoiState);
}
return saveAoiStateCommand;
}
}
private void InstantiateObjects()
{
initThread = new BackgroundWorker();
aoiStateList = new List<string>();
bluetapeList = new List<string>();
converter = new WaferIDConverter();
}
private void SetControlSettings()
{
initThread.WorkerReportsProgress = false;
initThread.WorkerSupportsCancellation = false;
initThread.DoWork += InitThread_DoWork;
initThread.RunWorkerCompleted += InitThread_RunWorkerCompleted;
}
private void PopulateAoiStateList()
{
aoiStateList.Add("True");
aoiStateList.Add("False");
aoiStateList.Add("NotBinned");
aoiStateList.Add("NeverAOI");
}
private void PopulateBluetapeList()
{
waferQueries = new WaferQueries(
DataLibrary.GetSingulationOne(selectedWafer));
foreach (BlueTape tape in waferQueries.GetBlueTapeList())
{
bluetapeList.Add(tape.Name);
}
OnPropertyChanged("BluetapeList");
}
private void SaveAoiState()
{
Mouse.OverrideCursor = Cursors.Wait;
singOne = new SingOneTable();
singOne.OverrideAoiState(selectedWafer, selectedBt, selectedAoiState);
Mouse.OverrideCursor = null;
MessageBox.Show(
"The AOI state of " + selectedBt + " from " + selectedWafer +
" has been successfully changed to " + selectedAoiState + "!",
"AOI State Saved", MessageBoxButton.OK, MessageBoxImage.Exclamation);
}
public void SelectWafer()
{
Mouse.OverrideCursor = Cursors.Wait;
SelectedWafer = tvwWaferList.SelectedValue.ToString();
PopulateBluetapeList();
Mouse.OverrideCursor = null;
}
private void InitThread_DoWork(object sender, DoWorkEventArgs e)
{
if (!handled)
{
PopulateAoiStateList();
tvwPresenter = new TreeViewPresenter(tvwWaferList, txtFilter, this);
tvwPresenter.WaferList = DataLibrary.GetWaferList();
handled = true;
}
}
private void InitThread_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
tvwPresenter.TreeView.DataContext = tvwPresenter.ProcessesAndWafers;
tvwPresenter.WaferListCache = tvwPresenter.ProcessesAndWafers;
tvwPresenter.ProcessArray = tvwPresenter.WaferListCache.ToArray();
//TODO: Update Status text block
}
}
Answered (2nd comment) by Dilshod:
The fix was to change my List to ObservableCollection.
Once I made that change, everything worked as expected; thanks Dilshod!
Binding WPF Drop-Down control dynamically (C#).
I am using the following simple solution for binding WPF drop-down (combo-box) to a Dictionary object programmatically (C#). In this particular example Dictionary contains the list of Countries with corresponding 2-digit Country Codes (keys):
Listing 1. Dictionary object contains list of Countries w/2-digit Country codes
Dictionary<string, string> _co = new Dictionary<string, string>();
_co.Add(String.Empty, String.Empty);
_co.Add("US", "United States");
_co.Add("CA", "Canada");
_co.Add("MX", "Mexico");
Listing 2. Binding Drop-down to Dictionary object (WPF/C#)
// binding to country list Dictionary object (_co)
_cmbCountry.ItemsSource = _co;
// Country 2-digit Code used as a key
_cmbCountry.SelectedValuePath = _dKey;
// Country Name (string to display)
_cmbCountry.DisplayMemberPath = _dValue;
// first index selected
_cmbCountry.SelectedIndex = 0;
// DropDownClosed event subscription using Lambda notation
_cmbCountry.DropDownClosed += (s, e) => ComboBox_Closed(s, e);
The code snippet above (Listing 2.) also shows how to subscribe to the control event using 'short-cut' Lambda style. Hope this will help. Regards, AB
PS. You can also find more information on Drop-Down control binding techniques in my article: Binding DropDownList to various data structures in Microsoft ASP.NET

Categories

Resources