I have a view which opens an idialog that I contain a datagrid. I select certain rows and send back those as a list to the view but all I search I just found ResultButton return for idialog. How I can send back a custom value like a list or anything else ?
My iDialog ViewModel :
public DelegateCommand<string> CloseCommand { get; set; }
public DelegateCommand<string> AttachCommand { get; set; }
private string _txtSearch;
public string txtSearch
{
get { return _txtSearch; }
set { SetProperty(ref _txtSearch, value); }
}
public List<GE_Drawing> SelectedDrawings { get; set; }
private ObservableCollection<GE_Drawing> _DrawingList= new ObservableCollection<GE_Drawing>();
public ObservableCollection<GE_Drawing> DrawingList
{
get { return _DrawingList; }
set { SetProperty(ref _DrawingList, value); }
}
private bool _IsSelected;
public bool IsSelected
{
get { return _IsSelected; }
set { SetProperty(ref _IsSelected, value); }
}
public GE_DrawingAttachViewModel()
{
LoadList();
CloseCommand = new DelegateCommand<string>(onClose);
AttachCommand = new DelegateCommand<string>(onAttach);
}
private void onAttach(string parameter)
{
ButtonResult result = new ButtonResult();
var records = DrawingList.Where(x => x.IsSelected == true).ToList();
if(records.Count>0)
{
SelectedDrawings = records;
}
//result = ButtonResult.OK;
//RaiseRequestClose(new DialogResult(result));
}
private void RaiseRequestClose(DialogResult dialogResult)
{
RequestClose?.Invoke(dialogResult);
}
private void onClose(string parameter)
{
ButtonResult result = new ButtonResult();
result = ButtonResult.Cancel;
RaiseRequestClose(new DialogResult(result));
}
private string _title="Drawing List";
public string Title
{
get => _title;
set => SetProperty(ref _title, value);
}
public event Action<IDialogResult> RequestClose;
public bool CanCloseDialog()
{
return true;
}
public void OnDialogClosed()
{
}
public void OnDialogOpened(IDialogParameters parameters)
{
}
public async void LoadList()
{
GenericDataService<GE_Drawing> generic = new GenericDataService<GE_Drawing>();
DrawingList.AddRange(await generic.GetAll());
}
}
As written above I have an OnAttach which should send back my SelectedDrawings variable to the view but I dont know how to do that.
I have found the answer... IdialogResult have parameter with a value could be set to in dialog and get the value in the callback using a key.
private void openDialog()
{
DialogParameters parameter = new DialogParameters();
_dialogService.ShowDialog("GE_DrawingAttach", parameter, r =>
{
if(r.Result==ButtonResult.OK)
{
DrawingList = r.Parameters.GetValue<List<GE_Drawing>>("DrawingList");
}
});
}
Related
How can I make sure that as soon as there is a change in the text field, the save button is enabled? or clicking edit (thus creating the button) the app enables editing and thus enabling the button,
and it has already been activated in case of insertion or deletion.
this a image of
app
Here is the code:
public GerenciarGenericoViewModel()
{
InserirProdutoCommand = new RelayCommand(InserirProduto);
ExcluirProdutoCommand = new RelayCommand(ExcluirProduto, CanExcluirProduto);
InserirUnidadeCommand = new RelayCommand(InserirUnidade);
ExcluirUnidadeCommand = new RelayCommand(ExcluirUnidade, CanExcluirUnidade);
InserirEmpresaCommand = new RelayCommand(InserirEmpresa);
ExcluirEmpresaCommand = new RelayCommand(ExcluirEmpresa, CanExcluirEmpresa);
InserirOperadorCommand = new RelayCommand(InserirOperador);
ExcluirOperadorCommand = new RelayCommand(ExcluirOperador, CanExcluirOperador);
SalvarCommand = new RelayCommand(Salvar, CanSalvar);
CancelarCommand = new RelayCommand(Cancelar);
ListaProdutos = new ObservableCollection<Produto>(ProdutosAccess.GetProdutos());
ListaUnidades = new ObservableCollection<UnidadeMedida>(ProdutosAccess.GetUnidadesMedida());
ListaEmpresas = new ObservableCollection<Empresa>(ProdutosAccess.GetEmpresas());
ListaOperadores = new ObservableCollection<Operador>(ProdutosAccess.GetOperadores());
}
public RelayCommand InserirProdutoCommand { get; }
public RelayCommand ExcluirProdutoCommand { get; }
public RelayCommand InserirUnidadeCommand { get; }
public RelayCommand ExcluirUnidadeCommand { get; }
public RelayCommand InserirEmpresaCommand { get; }
public RelayCommand ExcluirEmpresaCommand { get; }
public RelayCommand InserirOperadorCommand { get; }
public RelayCommand ExcluirOperadorCommand { get; }
int check = 0;
public RelayCommand SalvarCommand { get; }
public RelayCommand CancelarCommand { get; }
public ObservableCollection<Produto> ListaProdutos { get; }
public ObservableCollection<UnidadeMedida> ListaUnidades { get; }
public ObservableCollection<Empresa> ListaEmpresas { get; }
public ObservableCollection<Operador> ListaOperadores { get; }
private Produto _produtoSelecionado;
public Produto ProdutoSelecionado
{
get => _produtoSelecionado;
set => Set(() => ProdutoSelecionado, ref _produtoSelecionado, value);
}
private UnidadeMedida _unidadeSelecionada;
public UnidadeMedida UnidadeSelecionada
{
get => _unidadeSelecionada;
set => Set(() => UnidadeSelecionada, ref _unidadeSelecionada, value);
}
private Empresa _empresaSelecionada;
public Empresa EmpresaSelecionada
{
get => _empresaSelecionada;
set => Set(() => EmpresaSelecionada, ref _empresaSelecionada, value);
}
private Operador _operadorSelecionado;
public Operador OperadorSelecionado
{
get => _operadorSelecionado;
set => Set(() => OperadorSelecionado, ref _operadorSelecionado, value);
}
public void InserirProduto()
{
ListaProdutos.Add(new Produto());
check++;
}
public void ExcluirProduto()
{
ListaProdutos.Remove(ProdutoSelecionado);
check++;
}
public bool CanExcluirProduto()
{
return ProdutoSelecionado != null;
}
public void InserirUnidade()
{
ListaUnidades.Add(new UnidadeMedida());
check++;
}
public void ExcluirUnidade()
{
ListaUnidades.Remove(UnidadeSelecionada);
check++;
}
public bool CanExcluirUnidade()
{
return UnidadeSelecionada != null;
}
public void InserirEmpresa()
{
ListaEmpresas.Add(new Empresa());
check++;
}
public void ExcluirEmpresa()
{
ListaEmpresas.Remove(EmpresaSelecionada);
check++;
}
public bool CanExcluirEmpresa()
{
return EmpresaSelecionada != null;
}
public void InserirOperador()
{
ListaOperadores.Add(new Operador());
check++;
}
public void ExcluirOperador()
{
ListaOperadores.Remove(OperadorSelecionado);
check++;
}
public bool CanExcluirOperador()
{
return OperadorSelecionado != null;
}
public void Salvar()
{
var listaProdutos = ListaProdutos.ToList();
var listaUnidades = ListaUnidades.ToList();
var listaEmpresas = ListaEmpresas.ToList();
var listaOperadores = ListaOperadores.ToList();
listaProdutos = listaProdutos.Where(x => !string.IsNullOrWhiteSpace(x.Descricao)).ToList();
listaUnidades = listaUnidades.Where(x => !string.IsNullOrWhiteSpace(x.Descricao)).ToList();
listaEmpresas = listaEmpresas.Where(x => !string.IsNullOrWhiteSpace(x.Descricao)).ToList();
listaOperadores = listaOperadores.Where(x => !string.IsNullOrWhiteSpace(x.Nome)).ToList();
ProdutosAccess.SetListProdutos(listaProdutos);
ProdutosAccess.SetListUnidades(listaUnidades);
ProdutosAccess.SetListEmpresas(listaEmpresas);
ProdutosAccess.SetListOperadores(listaOperadores);
MessageBox.Show(messageBoxText: "Dados salvos com sucesso!",
caption: "Gerenciar Dados", button: MessageBoxButton.OK,
icon: MessageBoxImage.Information);
Sair();
}
public bool CanSalvar()
{
if (check == 0)
{
return false;
}
else
{
return true;
}
}
public void Cancelar()
{
Sair();
}
public void Sair()
{
Navigator.CloseWindowByDataContext(this);
}
}
As #BradleDotNET mentioned just set the UpdateSourceTrigger inside your TextBox Text binding to PropertyChanged and it should work.
I have a set of classes that I am using to deserialize JSON into. My program will periodically look for changes to this JSON file, and if it finds any, will push the new data to the properties of these classes using reflection.
I need to find any new items added to the collection of the Item2 class (SocialExportJSON.SocialExportData.Item2) after a successful update.
My JSON classes look like this (there are more but I want to avoid too big a wall of code):
public class Item2 : INotifyPropertyChanged
{
[JsonProperty("type")]
private string type;
public string Type
{
get
{
return type;
}
set
{
if (type != value)
{
type = value;
RaisePropertyChanged("Type");
}
}
}
[JsonProperty("id")]
private string id;
public string ID
{
get
{
return id;
}
set
{
if (id != value)
{
id = value;
RaisePropertyChanged("ID");
}
}
}
[JsonProperty("postedIso8601")]
private string postedIso8601;
public string PostedIso8601
{
get
{
return postedIso8601;
}
set
{
if (postedIso8601 != value)
{
postedIso8601 = value;
RaisePropertyChanged("PostedIso8601");
}
}
}
[JsonProperty("postedTimestamp")]
private object postedTimestamp;
public object PostedTimestamp
{
get
{
return postedTimestamp;
}
set
{
if (postedTimestamp != value)
{
postedTimestamp = value;
RaisePropertyChanged("PostedTimestamp");
}
}
}
[JsonProperty("engagement")]
private Engagement engagement;
public Engagement Engagement
{
get
{
return engagement;
}
set
{
if (engagement != value)
{
engagement = value;
RaisePropertyChanged("Engagement");
}
}
}
[JsonProperty("source")]
private Source2 source;
public Source2 Source
{
get
{
return source;
}
set
{
if (source != value)
{
source = value;
RaisePropertyChanged("Source");
}
}
}
[JsonProperty("author")]
private Author author;
public Author Author
{
get
{
return author;
}
set
{
if (author != value)
{
author = value;
RaisePropertyChanged("Author");
}
}
}
[JsonProperty("content")]
private Content content;
public Content Content
{
get
{
return content;
}
set
{
if (content != value)
{
content = value;
RaisePropertyChanged("Content");
}
}
}
[JsonProperty("location")]
private Location location;
public Location Location
{
get
{
return location;
}
set
{
if (location != value)
{
location = value;
RaisePropertyChanged("Location");
}
}
}
[JsonProperty("publication")]
private Publication publication;
public Publication Publication
{
get
{
return publication;
}
set
{
if (publication != value)
{
publication = value;
RaisePropertyChanged("Publication");
}
}
}
[JsonProperty("metadata")]
private Metadata metadata;
public Metadata Metadata
{
get
{
return metadata;
}
set
{
if (metadata != value)
{
metadata = value;
RaisePropertyChanged("Metadata");
}
}
}
//Event handling
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string property)
{
//Console.WriteLine("Updated");
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
}
}
public class SocialExportData : INotifyPropertyChanged
{
[JsonProperty("dataType")]
private string dataType;
public string DataType
{
get
{
return dataType;
}
set
{
if (dataType != value)
{
dataType = value;
RaisePropertyChanged("DataType");
}
}
}
[JsonProperty("id")]
private int id;
public int ID
{
get
{
return id;
}
set
{
if (id != value)
{
id = value;
RaisePropertyChanged("ID");
}
}
}
[JsonProperty("story")]
private Story story;
public Story Story
{
get
{
return story;
}
set
{
if (story != value)
{
story = value;
RaisePropertyChanged("Story");
}
}
}
[JsonProperty("order")]
private string order;
public string Order
{
get
{
return order;
}
set
{
if (order != value)
{
order = value;
RaisePropertyChanged("Order");
}
}
}
[JsonProperty("lifetime")]
private string lifetime;
public string Lifetime
{
get
{
return lifetime;
}
set
{
if (lifetime != value)
{
lifetime = value;
RaisePropertyChanged("Lifetime");
}
}
}
[JsonProperty("maxAge")]
private int maxAge;
public int MaxAge
{
get
{
return maxAge;
}
set
{
if (maxAge != value)
{
maxAge = value;
RaisePropertyChanged("MaxAge");
}
}
}
[JsonProperty("maxSize")]
private int maxSize;
public int MaxSize
{
get
{
return maxSize;
}
set
{
if (maxSize != value)
{
maxSize = value;
RaisePropertyChanged("MaxSize");
}
}
}
[JsonProperty("consumeCount")]
private int consumeCount;
public int ConsumeCount
{
get
{
return consumeCount;
}
set
{
if (consumeCount != value)
{
consumeCount = value;
RaisePropertyChanged("ConsumeCount");
}
}
}
[JsonProperty("consumeInterval")]
private int consumeInterval;
public int ConsumeInterval
{
get
{
return consumeInterval;
}
set
{
if (consumeInterval != value)
{
consumeInterval = value;
RaisePropertyChanged("ConsumeInterval");
}
}
}
[JsonProperty("items")]
private ObservableCollection<Item2> items;
public ObservableCollection<Item2> Items
{
get
{
return items;
}
set
{
if (items != value)
{
items = value;
RaisePropertyChanged("Items");
}
}
}
//Event handling
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string property)
{
//Console.WriteLine("Updated");
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
}
}
public class SocialExportJSON : INotifyPropertyChanged
{
[JsonProperty("id")]
private string id;
public string ID
{
get
{
return id;
}
set
{
if (id != value)
{
id = value;
RaisePropertyChanged("ID");
}
}
}
[JsonProperty("ttl")]
private int ttl;
public int TTL
{
get
{
return ttl;
}
set
{
if (ttl != value)
{
ttl = value;
RaisePropertyChanged("TTL");
}
}
}
[JsonProperty("serial")]
private long serial;
public long Serial
{
get
{
return serial;
}
set
{
if (serial != value)
{
serial = value;
RaisePropertyChanged("Serial");
}
}
}
[JsonProperty("formatType")]
private string formatType;
public string FormatType
{
get
{
return formatType;
}
set
{
if (formatType != value)
{
formatType = value;
RaisePropertyChanged("FormatType");
}
}
}
[JsonProperty("modifiedIso8601")]
private string modifiedIso8601;
public string ModifiedIso8601
{
get
{
return modifiedIso8601;
}
set
{
if (modifiedIso8601 != value)
{
modifiedIso8601 = value;
RaisePropertyChanged("ModifiedIso8601");
}
}
}
[JsonProperty("modifiedTimestamp")]
private long modifiedTimestamp;
public long ModifiedTimestamp
{
get
{
return modifiedTimestamp;
}
set
{
if (modifiedTimestamp != value)
{
modifiedTimestamp = value;
RaisePropertyChanged("ModifiedTimestamp");
}
}
}
[JsonProperty("timezone")]
private string timezone;
public string Timezone
{
get
{
return timezone;
}
set
{
if (timezone != value)
{
timezone = value;
RaisePropertyChanged("Timezone");
}
}
}
[JsonProperty("dataType")]
private string dataType;
public string DataType
{
get
{
return dataType;
}
set
{
if (dataType != value)
{
dataType = value;
RaisePropertyChanged("DataType");
}
}
}
[JsonProperty("exports")]
private ObservableCollection<SocialExportData> exports;
public ObservableCollection<SocialExportData> Exports
{
get
{
return exports;
}
set
{
if (exports != value)
{
exports = value;
RaisePropertyChanged("Exports");
}
}
}
//Event handling
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string property)
{
//Console.WriteLine("Updated");
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
}
}
In another class, I have a method to deserialize to a global instance of my JSON class. It looks like this:
public SocialExportJSON socialExportData;
private async void DownloadAndDeserializeJSONAsync()
{
try
{
//Create a web client with the supplied credentials
var exportClient = new WebClient { Credentials = new NetworkCredential(uName, pw), Encoding = Encoding.UTF8};
//Create a task to download the JSON string and wait for it to finish
var downloadTask = Task.Run(() => exportClient.DownloadString(new Uri(eURL)));
downloadTask.Wait();
//Get the string from the task
var JSONString = await downloadTask;
//Create a task to deserialize the JSON from the last task
var DeserializeTask = Task.Run(() => JsonConvert.DeserializeObject<SocialExportJSON>(JSONString));
DeserializeTask.Wait();
SocialExportJSON sej = await DeserializeTask;
//Check the timestamp first to see if we should change the data
if(socialExportData == null)
{
//Get the data from the task
socialExportData = await DeserializeTask;
}
else if(sej.ModifiedTimestamp != socialExportData.ModifiedTimestamp)
{
//Get the data from the task
SocialExportJSON newData = await DeserializeTask;
GetNewItems(newData);
SetNewData(newData);
//Call the exportUpdated event when the task has finished
exportUpdated();
}
}
catch (Exception e)
{
MessageBox.Show(e.Message.ToString());
}
}
In my SetNewData function, shown below, I use reflection to set the properties of my global class. Because I'm setting the whole collection rather than iterating through each of the properties in each of the classes, I can't use the CollectionChanged event to find new items.
public void SetNewData(SocialExportJSON newData)
{
//Loop through each of the properties and copy from source to target
foreach (PropertyInfo pi in socialExportData.GetType().GetProperties())
{
if (pi.CanWrite)
{
pi.SetValue(socialExportData, pi.GetValue(newData, null), null);
}
}
}
Is there a way I can modify my SetNewData function in such a way that it calls CollectionChanged? If not, what would be the best way to go about getting any new additions to my collection of Item2?
In my Main function. I create an instance of my class called SocialExport like so:
SocialExport s = new SocialExport("http://example.json", "example", "example");.
This class is where the global instance of my JSON class is contained, and my event handler is added like so
s.socialExportData.Exports[0].Items.CollectionChanged += CollectionChanged;
Then you are hooking up an event handler for the CollectionChanged event for that particular instance of ObservableCollection<Item2>.
If you create a new ObservableCollection<Item2>, you obviously must hook up an event handler to this one as well. The event handler that is associated with the old object won't be invoked when new items are added to the new instance.
So whenever a new ObservableCollection<Item2> is created, using deserialization or not, you should hook up a new event handler.
You could probably do this in your DownloadAndDeserializeJSONAsync method. The other option would be to create only one instance of the collection and remove and add items from/to this one.
I am stuck with a problem where I am checking network connectivity in an iOS app and trying to binding a boolean hasNetworkConnection in my view controller for it's view model.
View controller UpdateContentView.cs
// This file has been autogenerated from a class added in the UI designer.
using System;
using MvvmCross.iOS.Views;
using MvvmCross.Binding.BindingContext;
using Training.Core;
namespace EdwardsTraining.IOS
{
public partial class UpdateContentView : MvxViewController
{
public UpdateContentView(IntPtr handle) : base(handle)
{
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
var bindingSet = this.CreateBindingSet<UpdateContentView, UpdateContentViewModel>();
bindingSet.Bind(NoConnectionView).For(x => x.Hidden).To(vm => vm.HasConnection).WithConversion("ReverseBoolean");
bindingSet.Bind(UpdateInProgressView).For(x => x.Hidden).To(vm => vm.InProgress).WithConversion("ReverseBoolean");
bindingSet.Bind(UpdateAvailableView).For(x => x.Hidden).To(vm => vm.HasContentUpdate).WithConversion("ReverseBoolean");
bindingSet.Bind(CancelButton).For(x => x.Hidden).To(vm => vm.CancelVisible).WithConversion("ReverseBoolean");
bindingSet.Bind(RetryButton).To(vm => vm.DoRetryUpdate);
bindingSet.Bind(ConfirmButton).To(vm => vm.DoUpdate);
//bindingSet.Bind(iOSNetworkConnectivitiy).For(x => x.HasNetworkConnection).To(vm => vm.NetworkConnectivitiy).TwoWay()
//.For(vm => vm.HasNetworkConnection);
bindingSet.Bind(iOSNetworkConnectivitiy).To(vm => vm.NetworkConnectivitiy).TwoWay();
bindingSet.Apply();
_iOSnetworkConnectivity = new NetworkConnectivity()
{
HasNetworkConnection = Reachability.IsNetworkAvailable()
};
}
private NetworkConnectivity _iOSnetworkConnectivity { get; set; }
public NetworkConnectivity iOSNetworkConnectivitiy {
get{return _iOSnetworkConnectivity;}
set { _iOSnetworkConnectivity = value;
}
}
}
}
I would like to check for connectivity using my iOS specific code and bind the boolean returned to a a public view model property.
View Model
using System;
using System.Threading.Tasks;
using EdwardsTraining.BusinessLayer.Interfaces.Services;
using MvvmCross.Core.ViewModels;
using MvvmCross.Platform;
namespace Training.Core
{
public class UpdateContentViewModel : BaseViewModel
{
private IApplicationContentService _applicationContentService;
private ITrainingContentService _trainingContentService;
public bool _isNetworkAvailable { get; set; }
public UpdateContentViewModel(IApplicationContentService applicationContentService, ITrainingContentService trainingContentService)
{
_applicationContentService = applicationContentService ?? Mvx.Resolve<IApplicationContentService>();
_trainingContentService = trainingContentService ?? Mvx.Resolve<ITrainingContentService>();
IntialSetup();
}
protected void IntialSetup()
{
_cancelVisible = false;
_hasContentUpdate = true;
_inProgress = false;
}
public void SetNoConnection()
{
_cancelVisible = true;
_hasContentUpdate = false;
_inProgress = false;
}
public void SetInProgress()
{
_cancelVisible = false;
HasContentUpdate = false;
InProgress = true;
}
public void SetProgessComplete()
{
InProgress = false;
Task.Run(async () => await FinishedUpdating());
}
public async Task UpdateContent()
{
if (_networkConnectivity.HasNetworkConnection)
{
SetInProgress();
await _trainingContentService.UpdateTrainingContentAsync();
await _applicationContentService.UpdateContent();
SetProgessComplete();
await FinishedUpdating();
}
return;
}
public async Task FinishedUpdating()
{
Close(this);
}
public MvxCommand DoUpdate
{
get { return new MvxCommand(async () => await UpdateContent()); }
}
public MvxCommand DoRetryUpdate
{
get { return new MvxCommand(async () => await UpdateContent()); }
}
public MvxCommand CancelUpdate
{
get { return new MvxCommand(async () => await FinishedUpdating()); }
}
private bool _hasContentUpdate;
public bool HasContentUpdate
{
get { return _hasContentUpdate; }
set
{
_hasContentUpdate = value;
RaisePropertyChanged(() => HasContentUpdate);
}
}
private bool _hasConnection;
public bool HasConnection
{
get { return _hasConnection; }
set
{
_hasConnection = value;
RaisePropertyChanged(() => HasConnection);
}
}
private bool _inProgress;
public bool InProgress
{
get { return _inProgress; }
set
{
_inProgress = value;
RaisePropertyChanged(() => InProgress);
}
}
private bool _cancelVisible;
public bool CancelVisible
{
get { return _cancelVisible; }
set
{
_cancelVisible = value;
RaisePropertyChanged(() => CancelVisible);
}
}
private NetworkConnectivity _networkConnectivity { get; set; }
public NetworkConnectivity NetworkConnectivitiy
{
get { return _networkConnectivity; }
set {
_networkConnectivity = value;
RaisePropertyChanged(() => NetworkConnectivitiy);
}
}
}
public class NetworkConnectivity
{
public bool HasNetworkConnection { get; set; }
}
}
I have a problem with this line of code:
public async Task UpdateContent()
{
if (_networkConnectivity.HasNetworkConnection)
{
SetInProgress();
await _trainingContentService.UpdateTrainingContentAsync();
await _applicationContentService.UpdateContent();
SetProgessComplete();
await FinishedUpdating();
}
return;
}
if (_networkConnectivity.HasNetworkConnection) is already null even though I set two way binding. I'm new to MVVM cross for this reason I don't know if my approach is correct.
Is there anyone who could provide some help?
Nick
You need to explicitly tell the binding what property you want to bind on your NetworkConnectivity like:
bindingSet.Bind(iOSNetworkConnectivitiy).For(v => v.HasNetworkConnection).To(vm => vm.NetworkConnectivitiy).TwoWay();
However, the binding does not have any way to get notified that your NetworkConnectivity class has gotten any of its values updated. Hence you would have to extend that class to have some kind of event where it can get notified.
Then, you would have to write and register a Target Binding class.
Lets say you simply implement INotifyPropertyChanged in your NetworkConnectivity class:
public class NetworkConnectivity : MvxNotifyPropertyChanged
{
private bool _hasNetworkConnection;
public bool HasNetworkConnection {
get { return _hasNetworkConnection; }
set {
_hasNetworkConnection = value;
RaisePropertyChanged();
}
}
}
Then you create the following class in your iOS project:
public class NetworkConnectivityTargetBinding
: MvxPropertyInfoTargetBinding<NetworkConnectivity>
{
public NetworkConnectivityTargetBinding(object target, PropertyInfo targetPropertyInfo)
: base(target, targetPropertyInfo)
{
var view = View;
if (view == null)
{
MvxBindingTrace.Trace(MvxTraceLevel.Error,
"NetworkConnectivity is null in NetworkConnectivityTargetBinding");
}
else
{
view.PropertyChanged += HandleValueChanged;
}
}
private void HandleValueChanged(object sender, System.EventArgs e)
{
var view = View;
if (view == null)
return;
FireValueChanged(view.HasNetworkConnection);
}
public override MvxBindingMode DefaultMode => MvxBindingMode.TwoWay;
protected override void Dispose(bool isDisposing)
{
if (isDisposing)
{
var view = View;
if (view != null)
{
view.PropertyChanged -= HandleValueChanged;
}
}
base.Dispose(isDisposing);
}
}
Then in Setup.cs override FillTargetFactories:
protected override void FillTargetFactories(IMvxTargetBindingFactoryRegistry registry)
{
registry.RegisterPropertyInfoBindingFactory(typeof(NetworkConnectivityTargetBinding),
typeof(NetworkConnectivity), "HasNetworkConnection");
base.FillTargetFactories(registry);
}
Now the TwoWay binding should work. You should also be able to remove the .For(v => v.HasNetworkConnection) from you binding expression.
Is there a way to map database fields to OOP complex type fields with Enterprise Library. I am calling stored procedures that retrieves all data that I would like to store into custom class.
Here I retrieve data from sp:
IEnumerable<WorkHistoryGrid> data = new List<WorkHistoryGrid>();
return db.ExecuteSprocAccessor<WorkHistoryGrid>("PensionPDF_RetrieveParticipantWorkHistoryForFund", pensionId, fund);
And here is my class
public class WorkHistoryGrid : BindableBase
{
private string _rateType;
private string _fundType;
private string _employer;
private string _employerName;
private string _local;
private string _dateBalanced;
private string _plan;
private string _fund;
private WorkHistoryGridMergeData _mergeData;
#region Properties
public WorkHistoryGridMergeData MergeData
{
get { return _mergeData; }
set { SetProperty(ref _mergeData, value); }
}
public string RateType
{
get { return _rateType; }
set { SetProperty(ref _rateType, value); }
}
public string FundType
{
get { return _fundType; }
set { SetProperty(ref _fundType, value); }
}
public string Employer
{
get { return _employer; }
set { SetProperty(ref _employer, value); }
}
public string EmployerName
{
get { return _employerName; }
set { SetProperty(ref _employerName, value); }
}
public string Local
{
get { return _local; }
set { SetProperty(ref _local, value); }
}
public string DateBalanced
{
get { return _dateBalanced; }
set { SetProperty(ref _dateBalanced, value); }
}
public string Plan
{
get { return _plan; }
set { SetProperty(ref _plan, value); }
}
public string Fund
{
get { return _fund; }
set { SetProperty(ref _fund, value); }
}
}
}
}
It works fine if I would create one class with all database fields, but I would like to have more control over it by mapping database fields to custom complex type properties.
Here is the answer in my case, in case someone would look for similar solution:
var workHistoryGridSetMapper = new WorkHistoryGridSetMapper();
db.ExecuteSprocAccessor<WorkHistoryGrid>("PensionPDF_RetrieveParticipantWorkHistory", workHistoryGridSetMapper, pensionId);
IResultSetMapper
public class WorkHistoryGridSetMapper : IResultSetMapper<WorkHistoryGrid>
{
public IEnumerable<WorkHistoryGrid> MapSet(IDataReader reader)
{
List<WorkHistoryGrid> workHistoryLst = new List<WorkHistoryGrid>();
using (reader) // Dispose the reader when we're done
{
while (reader.Read())
{
WorkHistoryGrid workHist = new WorkHistoryGrid();
workHist.Amount = reader.GetValue(reader.GetOrdinal("Amount")).ToString();
workHist.DateBalanced = reader.GetValue(reader.GetOrdinal("DateBalanced")).ToString();
workHist.Employer = reader.GetValue(reader.GetOrdinal("Employer")).ToString();
workHist.EmployerName = reader.GetValue(reader.GetOrdinal("EmployerName")).ToString();
workHist.Fund = reader.GetValue(reader.GetOrdinal("Fund")).ToString();
workHist.FundType = reader.GetValue(reader.GetOrdinal("FundType")).ToString();
workHist.Hours = reader.GetValue(reader.GetOrdinal("Hours")).ToString();
workHist.Local = reader.GetValue(reader.GetOrdinal("Local")).ToString();
workHist.Period = reader.GetValue(reader.GetOrdinal("Period")).ToString();
workHist.Plan = reader.GetValue(reader.GetOrdinal("Plan")).ToString();
workHist.RateAmount = reader.GetValue(reader.GetOrdinal("RateAmount")).ToString();
workHist.RateType = reader.GetValue(reader.GetOrdinal("RateType")).ToString();
workHist.Status = reader.GetValue(reader.GetOrdinal("Status")).ToString();
workHist.WorkMonth = reader.GetValue(reader.GetOrdinal("WorkMonth")).ToString();
workHist.MergeData = new WorkHistoryGridMergeData
{
MergeDateMerged = reader.GetValue(reader.GetOrdinal("MergeDateMerged")).ToString(),
MergeLastUpdated = reader.GetValue(reader.GetOrdinal("MergeLastUpdated")).ToString(),
MergeLastUpdatedUserId = reader.GetValue(reader.GetOrdinal("MergeLastUpdatedUserId")).ToString(),
MergeLastUpdatedUserType = reader.GetValue(reader.GetOrdinal("MergeLastUpdatedUserType")).ToString(),
MergeNewSsn = reader.GetValue(reader.GetOrdinal("MergeNewSsn")).ToString(),
MergeNotes = reader.GetValue(reader.GetOrdinal("MergeNotes")).ToString(),
MergeOldSsn = reader.GetValue(reader.GetOrdinal("MergeOldSsn")).ToString(),
MergeTrustId = reader.GetValue(reader.GetOrdinal("MergeTrustId")).ToString(),
MergeUserName = reader.GetValue(reader.GetOrdinal("MergeUserName")).ToString()
};
workHistoryLst.Add(workHist);
};
}
return workHistoryLst;
}
}
I am wondering if anyone tell me why the filtering on Queries which is a list of ObservableCollection does not work in my below code? Queries.List.Where(x => x.Name.Equals(value)) always has the whole list..no filtering. Is there something wrong with my lambda expression?
ViewModel:
namespace DataRetrieval.ViewModel
{
public class QueriesViewModel:BindableBase
{
public QueriesViewModel()
{
Queries = new Queries();
for (int i = 0; i < 5; ++i)
{
var query = new Query { Name = "Query "+i.ToString() };
Queries.List.Add(query);
}
}
private Queries _queries;
public Queries Queries
{
get { return _queries; }
set { SetProperty(ref _queries, value); }
}
private string _filter1;
public string Filter1
{
get { return _filter1; }
set {
SetProperty(ref _filter1, value);
filterlist(Filter1);
}
}
private void filterlist(string value)
{
Queries.List.Where(x => x.Name.Equals(value));
}
}
}
Model:
public class Queries : BindableBase
{
private ObservableCollection<Query> _list;
public ObservableCollection<Query> List
{
get { return _list ?? (_list = new ObservableCollection<Query>()); }
set { SetProperty(ref _list, value); }
}
}
public class Query:BindableBase
{
private string _name;
public string Name
{
get { return _name; }
set {
SetProperty(ref _name, value);
}
}
private string _type;
public string Type
{
get { return _type; }
set { SetProperty(ref _type, value); }
}
private QDatatables _tables;
public QDatatables Tables
{
get { return _tables; }
set { SetProperty(ref _tables, value); }
}
}
Queries.List = new ObservableCollection<Query>(Queries.List.Where(x => x.Name.Equals(value)));
Queries.List.Where() returns a new value, so either set it back to Queries.List (as #Valera said in his comment), or return it like so:
Queries.List = Queries.List.Where(x => x.Name.Equals(value));
or
return Queries.List.Where(x => x.Name.Equals(value));
Edit: returning wouldn't work because it is inside a void function, and you'd have to change that, or use #Valera's method.