Howto let ReactiveCommands observe their own IsExecuting observable - c#

I have several commands in my ViewModel and I want to have the CanExecute of each button to be bound to an observable busy which is defined as none of the buttons is currently executing.
The following is what I came up with, but obviously it runs into a NullReferenceException.
busy = Observable.CombineLatest(this.PlayCommand.IsExecuting, this.PauseCommand.IsExecuting, (play, pause) => play && pause);
this.PauseCommand = new ReactiveCommand(busy.Select(b => !b));
this.PlayCommand = new ReactiveCommand(busy.Select(b=> !b));
Also the CanExecuteObservable property on ReactiveCommand is readonly, so I need to define an IObservable before I initialize the commands.
Any ideas on how to solve this chicken and egg problem? A better way of observing busy state for a ViewModel (or a collection of ViewModels) would be appreciated also :-)

I would set up a proxy via using a Subject:
var areAllAvailable = new BehaviorSubject<bool>(true);
PauseCommand = new ReactiveCommand(areAllAvailable);
PlayCommand = new ReactiveCommand(areAllAvailable);
Observable.CombineLatest(PauseCommand.IsExecuting, PlayCommand.IsExecuting,
(pa,pl) => !(pa || pl))
.Subscribe(allAreAvailable);

Related

WinUI: Completed callback for UIElement.Transitions property

As the title says, is there a way to be notified when the transition in TransitionCollection that is assigned to UIElement.Transitions is completed?
It would be great if a simple sample code block is provided. Thanks in advance!
Transition class: https://learn.microsoft.com/en-us/uwp/api/windows.ui.xaml.media.animation.transition?view=winrt-22621
UIElement.Transitions property: https://learn.microsoft.com/en-us/uwp/api/windows.ui.xaml.uielement.transitions?view=winrt-22621
PaneThemeTransition transition = new PaneThemeTransition();
Transitions = new TransitionCollection { transition };

how to pass a list between pages xamarin.forms?

I have a list of objects that should be passed to another view but I don't know how I can do that in Xamarin.forms, I think I should to use setBinding, but its the only thing I say in this case.
Thank you.
List<Localizacao> localizacaoList = new List<Localizacao>(); ;
if (localizacao != null && lojaPerto != null)
{
localizacaoList = new List<Localizacao>();
Localizacao loc = new Localizacao();
loc.latitude = Double.Parse(lojaPerto.latitude);
loc.longitude = Double.Parse(lojaPerto.longitude);
localizacaoList.Add(loc);
localizacaoList.Add(localizacao);
}
var secondPage = new Views.ComoChegarView ();
secondPage.BindingContext = localizacaoList;
await Navigation.PushAsync(secondPage);
In fact, I sent, but I can't get it again in the other view
If you are not using any additional framework, maybe you can try using constructor parameters.
public partial class ComoChegarView
{
...
private List<Localizacao> Locals{get;set;}
public ComoChegarView(List<Localizacao> locals)
{
InitializeComponent(); //standard code that mix xaml and code behind
this.Locals = locals; //store the data in property
this.BindingContext = this; //Set the binding context
}
}
So you can pass the value when you construct the page.
List<Localizacao> localizacaoList = new List<Localizacao>(); ;
if (localizacao != null && lojaPerto != null)
{
localizacaoList = new List<Localizacao>();
Localizacao loc = new Localizacao();
loc.latitude = Double.Parse(lojaPerto.latitude);
loc.longitude = Double.Parse(lojaPerto.longitude);
localizacaoList.Add(loc);
localizacaoList.Add(localizacao);
}
var secondPage = new Views.ComoChegarView (localizacaoList);
await Navigation.PushAsync(secondPage);
Remember that update your binding in XAML to reflect property access (for example)
<ListView ItemsSource="{Binding Locals}">...</ListView>
What you want to achieve is perfectly supported by all serious MVVM libraries.
1) a view do not pass anything to another view, it is the job of the ViewModels
2) in a MVVM context you can use many techniques to send ou pass data from one ViewModel to another, the main being : MVVM messenger (there's one include in Xamarin.Forms) or dependency injection in the the ViewModel constructor (using an IoC container what most MVVM libraries are offering, using Unity, DryIoc, ...).
It is certainly hard to do if you do not master MVVM pattern but you should take a little time to study this pattern and some libraries as Prism. You will quickly see the benefit of such an approach and will be very happy to write code more efficiently (and find in a minute quick and clean solutions to problems like the one you're talking about here).

Understanding why TPL Task can update UI withOUT FromCurrentSynchronizationContext

I am doing some TPL in VS2012, WPF with MVVM. I have a question that I think I know the answer to but wanted to know for sure. Consider this snippet:
TaskCanceller = new CancellationTokenSource();
TaskLoader = Task<object>.Factory.StartNew(() =>
{
//Test the current query
DataRepository dr = new DataRepository(DataMappingSelected);
string test = dr.TestMappingConnection();
if (test.IsNotNullEmpty())
throw new DataConnectionException(test);
//Create the CSV File
DataQueryCsvFile CsvFile = new DataQueryCsvFile();
CsvFile.FileName = IO.Path.GetFileName(FilePath);
CsvFile.FilePath = IO.Path.GetDirectoryName(FilePath);
CsvFile.DataMapping = DataMappingSelected;
CsvFile.DataBrowserQuery = DataQueryHolder;
//Allow for updates to the UI
CsvFile.PageExportComplete += (s, e) =>
{
if (TaskCanceller.IsCancellationRequested)
(s as DataQueryCsvFile).IsSaveCancellationRequested = true;
StatusData = String.Format("{0} of {1} Complete", e.ProgressCount, e.TotalCount);
StatusProgress = (100 * e.ProgressCount / e.TotalCount);
};
CsvFile.SaveFile();
return CsvFile;
});
I have a class DataQueryCsvFile. Its intent is to create a CSV text file based off a passed set of query parameters the results of which can be very large. So the export "paginates" the table produced by the query so it does not blow the users memory. Among its members is an Event called PageExportComplete which is called whenever a "Page" is written to a file - say 1000 records at a time. The code below uses this event to update a progress indicator on the UI.
The progress indicators (StatusData and StatusProgress) are declared in the VM with appropriate Notification to let the View know when they are changed. For example:
public string StatusData
{
get { return _StatusData; }
set { NotifySetProperty(ref _StatusData, value, () => StatusData); }
}
private string _StatusData;
Here is my question - as is, this works very well. But why since I did NOT declare the Task to run or update via the UI thread (FromCurrentSynchronizationContext) in a ContinueWith.
Is it because the MVVM pattern? In other words, because the properties being updated are local to the VM and because they have the notification to update the View and because of the lose coupling via bindings its works? Or am I just lucky due to the circumstances and I should go through the trouble of declaring a ContinueWith to update progress on the UI thread?
UI related stuff can only be updated from UI thread whereas any CLR property binded to UI can be updated from background thread, they don't have thread affinity issue.
Like you posted in your sample, you are only updating View model properties from background thread which is perfectly fine but if you try updating Progress bar text directly, it will fall miserably since progressBar is UI component and can only be updated from UI thread.
Say you have TextBlock binded to Name property in ViewModel class:
<TextBlock x:Name="txt" Text="{Binding Name}"/>
If you try to update text directly, you will get famous thread affinity issue:
Task.Factory.StartNew(() => txt.Text = "From background");
But in case you try to update ViewModel Name property, it will work fine since no UI stuff is access from background thread here:
ViewModelClass vm = DataContext as ViewModelClass;
Task.Factory.StartNew(() => vm.Name = "From background");

Wpf application and Threads

I have problem with my GUI and Threads.
The GUI contains DataGrid. Every X time the program do some query and getting a list of items that I want to fill into the DataGrid.
So far so good:
private void loadTaskList() //Call every X time
{
List<myObject> myList = myquery();
this.Dispatcher.Invoke((Action)(() =>
{
TaskListTable.Items.Clear(); //Clear the DataGrid
foreach (myObject O in myList) //Add the items from the new query.
{
TaskListTable.Items.Add(O);
}
}));
FindSelectionObject(); // <-- see next explanation.
}
When the user click on one of the objects in the datagrid, the line color changed (it works fine), but when the program reload the table,The painted line disappears (Becuse I clear and add new objects).
To deal with it, I created the function FindSelectionObject():
private void FindSelectionObject()
{
this.Dispatcher.Invoke((Action)(() =>
{
this.SelectedIndex = TaskListTable.Items.IndexOf((myObject)lastSelectionObject); //find index of the new object that equels to the last selection object.
var row = TaskListTable.ItemContainerGenerator.ContainerFromIndex(SelectedIndex) as DataGridRow; //get the row with the index
row.Background = Brushes.LightGoldenrodYellow; //repaint
}));
}
The problem: Everything works fine, but sometimes when the program reloads, the line flashes per second and then highlighted back, and sometimes it's not painting it at all (untill the next reload).
I can't understand why this is happening. I think maybe the FindSelectionObject() begins to run before the loadTaskList() ends to invoke all and add the new objects into the datagrid.
But if so - Why? And how can I fix it?
In the bottom line, I want that after every reload the line re-paint immediately..
Thanks for any advice!
A few things to think about:
You should keep in mind that the DataGrid uses virtualization, which means that each item in your items source does not get its very own UI element. The UI elements are created to fill the visible area, and then re-used depending on which data-source item is currently bound to each one (this changes when you scroll for instance or change the items source). This may cause you problems in the future if you use your current approach, so keep this in mind.
The other thing is that the DataGrid may require more "cycles" of the layout process in order to update its UI. You may simply be calling FindSelectionObject prematurely. You have queued FindSelectionObject right after the invocation in loadTaskList. If the DataGrid needs to perform some actions which are queued on the dispatcher after the items source has changed, these will execute after the invocation in FindSelectionObject.
Try this instead:
private void loadTaskList() //Call every X time
{
List<myObject> myList = myquery();
this.Dispatcher.Invoke((Action)(() =>
{
TaskListTable.Items.Clear(); //Clear the DataGrid
foreach (myObject O in myList) //Add the items from the new query.
{
TaskListTable.Items.Add(O);
}
// The items of the grid have changed, NOW we QUEUE the FindSelectionObject
// operation on the dispatcher.
FindSelectionObject(); // <-- (( MOVE IT HERE )) !!
}));
}
EDIT: OK, so if this fails then maybe this will cover the case in which the above solution fails: subscribe to the LoadingRow event of DataGrid and set the appropriate background color if the row is the selected one. So in the cases when new rows are created this event will be called (due to virtualization it is not called per item in items source, but per actual row UI element). In the event args you will have access to the created DataGridRow instance.
I think this issue could be a visual thread synchronization. For this you can create and use a method similar like this:
public void LockAndDoInBackground(Action action, string text, Action beforeVisualAction = null, Action afterVisualAction = null)
{
var currentSyncContext = SynchronizationContext.Current;
var backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += (_, __) =>
{
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");
currentSyncContext.Send((t) =>
{
IsBusy = true;
BusyText = string.IsNullOrEmpty(text) ? "Espere por favor..." : text;
if (beforeVisualAction != null)
beforeVisualAction();
}, null);
action();
currentSyncContext.Send((t) =>
{
IsBusy = false;
BusyText = "";
if (afterVisualAction != null)
afterVisualAction();
}, null);
};
backgroundWorker.RunWorkerAsync();
}
IsBusy and BusyText are particular properties, that you can remove. The action variable will be the action to do in background (load your items for instance). beforeVisualAction and afterVisualAction are the visual actions you may want to do before and after the background action. Here are any visual update, for instance select your item, change color, set a view model variable that raise a binding update,... (any action that update the view).
Hope this method helps.
Are you maintaining the reference to lastSelectionObject somewhere? You say you're adding new objects, if they are truly new then the reference will be different and the reference comparison happening in IndexOf will not find it.

How to force validation errors update on View from ViewModel using IDataErrorInfo?

I have a MVVM-based Window with many controls, and my Model implements IDataErrorInfo.
There is also a SaveCommand button, which performs validation by analysing Model.Error property.
The view displays the default red border around controls with errors only when I change the value of a particular control, or when I notify about the change of that property using PropertyChanged.
How can I force View to display all Validation errors even when I didn't touch the controls?
All my validation bindings include ValidatesOnDataErrors=True, NotifyOnValidationError=True.
I know one solution is to have an aggregate box with all the errors, but I would prefer to display errors on per-control basis.
I don't want to trigger Model.NotifyPropertyChanged for each bound property from ViewModel.
I use WPF 4.0, not Silverlight, so INotifyDataErrorInfo won't work.
You mention that you don't want to raise property changed for the properties you bind to, but that's really the simplest way to accomplish this. Calling PropertyChanged with no parameter will raise for all properties in your viewmodel.
Alternatively you can update the bindings (and force revalidation) on any control like this:
myControl.GetBindingExpression(ControlType.ControlProperty).UpdateSource();
The best solution I've found so far that works is to change DataContext to null and back to the instance of ViewModel.
This triggers the update for controls on the view that has DataContext bound to InnerViewModel:
public void ForceUpdateErrors() {
var tmpInnerVM = _mainViewModel.InnerViewModel;
_mainViewModel.InnerViewModel = null;
_mainViewModel.InnerViewModel = tmpInnerVM;
}
It's recommended to check if no data is lost after this trick. I had a case that this code triggered source update for ComboBox.SelectedItem with null but I managed to solve it. It was caused by using a resource-based BindingProxy and the order of DataContext=null propagation across control hierarchy.
This 'Hack' worked for me temporarily, to force the InotifyChanged event, just assign that control back it's own content. Do this before evaluating the HasError function of bindings. For example a textbox would be:
((TextBox)child).Text = ((TextBox)child).Text;
And then a complete example(before I hear this is not true MVVM, I directly got a handle on the grid for ease of showing this code snipet)
public bool Validate()
{
bool hasErr = false;
for (int i = 0; i != VisualTreeHelper.GetChildrenCount(grd); ++i)
{
DependencyObject child = VisualTreeHelper.GetChild(grd, i);
if (child is TextBox)
{
bool pp = BindingOperations.IsDataBound(child, TextBox.TextProperty);
if (pp)
{
((TextBox)child).Text = ((TextBox)child).Text;
hasErr = BindingOperations.GetBindingExpression(child, TextBox.TextProperty).HasError;
System.Collections.ObjectModel.ReadOnlyCollection<ValidationError> errors = BindingOperations.GetBindingExpression(child, TextBox.TextProperty).ValidationErrors;
if (hasErr)
{
main.BottomText.Foreground = Brushes.Red;
main.BottomText.Text = BindingOperations.GetBinding(child, TextBox.TextProperty).Path.Path.Replace('.', ' ') + ": " + errors[0].ErrorContent.ToString();
return false;
}
}
}
if (child is DatePicker)
{
...
}
}
return true;
}

Categories

Resources