Caliburn.Micro not updating UI - c#

I'm trying to build simple utility with caliburn micro and wpf. This simple code:
public bool CanTransfer
{
get { return this.canTransfer; }
set
{
this.NotifyOfPropertyChange(() => this.CanTransfer);
this.canTransfer = value;
}
}
public void Transfer()
{
Task.Factory.StartNew(this.Process);
}
private void Process()
{
this.CanTransfer = false;
Thread.Sleep(5000);
this.CanTransfer = true;
}
Does the following - Transfer button remains disabled, but I'd expect it to be enabled 5 seconds after, what am I doing wrong?

Swap those lines in CanTransfer setter method - now you first say something has changed while it actually hasn't and then you change it:
public bool CanTransfer
{
get { return this.canTransfer; }
set
{
this.canTransfer = value;
this.NotifyOfPropertyChange(() => this.CanTransfer);
}
}
I usually use method like ChangeAndNotify<T> (the only annoyance is declaration of the field), the code can be seen here:
private bool _canTransfer;
public string CanTransfer
{
get { return _canTransfer; }
set
{
PropertyChanged.ChangeAndNotify(ref _canTransfer, value, () => CanTransfer);
}
}

You are missing a notifiation:
this.NotifyOfPropertyChange(() => this.CanTransfer);
I hope I got the syntax right, I am typing from memory.
This basically tells WPF "Hey something changed, go and look at the new value".

Related

Creating a custom property class for multiple re-use within a class

Suppose I have a C# class that has multiple properties that all look like this:
private bool _var1Dirty = true;
private Double? _var1;
public Double? Var1
{
get
{
if (_var1Dirty)
{
_var1 = Method_Var1();
_var1Dirty = false;
}
return _var1;
}
}
And the only differences between each of these properties would be:
The type of return var (in this case Double?, but could just as easily be int, string, etc)
The method call - Method_Var1() (Each property would have a different one)
Is there any way I could write this as a custom class?
Something along the lines of:
public class Prop
{
public delegate T Func();
private bool _dirty = true;
private T _val;
public T Val
{
get
{
if (_dirty)
{
_val = Func;
_dirty = false;
}
return _val;
}
}
}
And then I could pass into it the:
Return type T
Method Func
(PS - I know this won't compile / is dead wrong, but I wanted to give an idea of what I'm looking for)
Any help / guidance would be really appreciated.
Thanks!!!
You're close. You can do something along the lines of this:
public class Dirty<T>
{
public Dirty(Func<T> valueFactory)
{
this.valueFactory = valueFactory;
dirty = true;
}
private Func<T> valueFactory;
private bool dirty;
private T value;
public T Value
{
get
{
if (dirty)
{
value = valueFactory();
dirty = false;
}
return value;
}
}
}
And you consume it like this:
Dirty<double?> dirtyDouble = new Dirty<double?>(() => SomethingThatReturnsADouble());
double? value = dirtyDouble.Value;
I'm not sure what the dirty checking actually does, but if you need someone more complicated than a bool you can always turn it into some Func<T> the checks for dirtiness.
Edit:
Given #mikez comment and your answer, you can save yourself the creation of the Dirty<T> class by using the built in Lazy<T>, which also guarantess thread safety:
public class F
{
private Lazy<double?> lazyDouble = new Lazy<double?>(() =>
MethodThatReturnsNullableDouble(), true);
public double? Value
{
get
{
return lazyDouble.Value;
}
}
}

WPF MVVM Light - Cancel property change in viewmodel - RaisePropertyChanged even if value is same as before

I have a property(in viewmodel) bound to a combobox.
When the viewmodel property changes, it uses the Messenger to tell another viewmodel about this.
This other viewmodel then decides if this is ok, if not i want to cancel and send the old value back up to the view.
I guess i can do this by setting the value to the new one first, then set it back. But is there a more elegant soulution?
Failing code
public DeckType SelectedDeckType
{
get { return _selectedDeckType; }
set
{
DeckTypeMessage deckTypeMessage = new DeckTypeMessage(value);
Messenger.Default.Send(deckTypeMessage);
if (deckTypeMessage.IsCancel)
{
//Some background magic finds out the value of this property is still the same?
//So the combobox does not revert!
//I can hack this but is there some way to force this?
RaisePropertyChanged();
return;
}
_selectedDeckType = value;
RaisePropertyChanged();
}
}
I managed to fix it with this workaround, but i dont like it :(
At first glance it seams to be incorrect, but the call stack makes it this way
Using oneway binding on SelectedItem and Interaction Trigger with command
Hacky workaround
public DeckType SelectedDeckType
{
get { return _selectedDeckType; }
set
{
_selectedDeckType = value;
RaisePropertyChanged();
}
}
public ICommand SelectedDeckTypeChangedCommand { get; private set; }
private void ExecuteSelectedItemChangedCommand(DeckType aDeckType)
{
try
{
if (_previousSelectedDeckType == aDeckType)
{
return;
}
_previousSelectedDeckType = aDeckType;
DeckTypeMessage deckTypeMessage = new DeckTypeMessage(this, aDeckType);
Messenger.Default.Send(deckTypeMessage);
if (deckTypeMessage.IsCancel)
{
SelectedDeckType = _selectedDeckType;
_previousSelectedDeckType = _selectedDeckType;
return;
}
SelectedDeckType = aDeckType;
}
catch (Exception ex)
{
NotifyMediator.NotifiyException(new NotifyMediator.NotifyInformation(NotifyMediator.NotificationLevel.Error, ex));
}
}
Kind Regards
You need to use Dispatcher.BeginInvoke to perform the reversal of the user action.
Basically, when the user selects the item on the combo box, any attempt to reject that value will be ignored by WPF. However, if you wait until all the code relating to data binding finishes, then you can basically start a new binding activity. This is what Dispatcher.BeginInvoke does. It allows your reset of the selected item to be postponed until the binding engine has finished its work.
Example:
public class MainViewModel : ViewModelBase
{
private string _selectedItem;
public List<string> Items { get; private set; }
public string SelectedItem
{
get { return _selectedItem; }
set
{
if (value == _selectedItem) return;
var previousItem = _selectedItem;
_selectedItem = value;
var isInvalid = value == "Bus"; // replace w/ your messenger code
if (isInvalid)
{
Application.Current.Dispatcher.BeginInvoke(
new Action(() => ResetSelectedItem(previousItem)),
DispatcherPriority.ContextIdle,
null);
return;
}
RaisePropertyChanged();
}
}
public MainViewModel()
{
Items = new[] { "Car", "Bus", "Train", "Airplane" }.ToList();
_selectedItem = "Airplane";
}
private void ResetSelectedItem(string previousItem)
{
_selectedItem = previousItem;
RaisePropertyChanged(() => SelectedItem);
}
}

How to sort a DataGridView that is bound to a collection of custom objects?

So I have been following this guide for data binding on Windows Forms controls (MAD props to the author, this guide is great), and I have used this to create a custom class and bind a DataGridView to a collection of this class:
class CompleteJobListEntry
{
private string _jobName;
private Image _jobStatus;
private DateTime _jobAddedDate;
private string _jobAddedScanner;
private string _jobAddedUser;
private string _jobLastActivity;
private DateTime _jobActivityDate;
private string _jobActivityUser;
public string JobName { get { return _jobName; } set { this._jobName = value; } }
public Image JobStatus { get { return _jobStatus; } set { this._jobStatus = value; } }
public DateTime JobAddedDate { get { return _jobAddedDate; } set { this._jobAddedDate = value; } }
public string JobAddedScanner { get { return _jobAddedScanner; } set { this._jobAddedScanner = value; } }
public string JobAddedUser { get { return _jobAddedUser; } set { this._jobAddedUser = value; } }
public string JobLastActivity { get { return _jobLastActivity; } set { this._jobLastActivity = value; } }
public DateTime JobActivityDate { get { return _jobActivityDate; } set { this._jobActivityDate = value; } }
public string JobActivityUser { get { return _jobActivityUser; } set { this._jobActivityUser = value; } }
}
At this point, I import a bunch of data from various SQL databases to populate the table, and it turns out great. The guide even provides an excellent starting point for adding filters, which I intend to follow a bit later. For now, though, I am stuck on the sorting of my newly generated DataGridView. Looking around, I've discovered that the DataGridView has its own Sort method, usable like:
completeJobListGridView.Sort(completeJobListGridView.Columns["JobName"], ListSortDirection.Ascending);
However, when I try to do this, I get an InvalidOperationException that tells me "DataGridView control cannot be sorted if it is bound to an IBindingList that does not support sorting." I've found both the IBindingList and IBindingListView interfaces, but making my class inherit either of these interfaces doesn't solve the problem.
How do I do this? I am completely stuck here...
If your data is in a collection, you should be able to use the BindingListView library to easily add sorting capabilities to your DGV. See How do I implement automatic sorting of DataGridView? and my answer to How to Sort WinForms DataGridView bound to EF EntityCollection<T> for more information and code snippets.

NavigationService WithParam of Caliburn Micro for WP

As is well known, CM doesn't support passing a object of complex type through NavigationService like MVVM Light. So I searched for a workaround and did it like this.
There are two viewmodels: MainPageViewModel and SubPageViewModel.
I first defined 3 classes, namely GlobalData, SnapshotCache and StockSnapshot. StockSnapshot is the type of which the object I want to pass between the 2 viewmodels.
public class SnapshotCache : Dictionary<string, StockSnapshot>
{
public StockSnapshot GetFromCache(string key)
{
if (ContainsKey(key))
return this[key];
return null;
}
}
public class GlobalData
{
private GlobalData()
{
}
private static GlobalData _current;
public static GlobalData Current
{
get
{
if (_current == null)
_current = new GlobalData();
return _current;
}
set { _current = value; }
}
private SnapshotCache _cachedStops;
public SnapshotCache Snapshots
{
get
{
if (_cachedStops == null)
_cachedStops = new SnapshotCache();
return _cachedStops;
}
}
}
public class StockSnapshot
{
public string Symbol { get; set; }
public string Message { get; set; }
}
Next, I call the navigation service on MainPageViewModel like this:
StockSnapshot snap = new StockSnapshot {Symbol="1", Message = "The SampleText is here again!" };
GlobalData.Current.Snapshots[snap.Symbol] = snap;
NavigationService.UriFor<SubPageViewModel>().WithParam(p=>p.Symbol,snap.Symbol).Navigate();
And on SubPageViewModel I've got this:
private string _symbol;
public string Symbol
{
get { return _symbol; }
set
{
_symbol = value;
NotifyOfPropertyChange(() => Symbol);
}
}
public StockSnapshot Snapshot
{
get { return GlobalData.Current.Snapshots[Symbol]; }
}
And that's where the problem lies. When I run the program, I find out that it always runs to the getter of Snapshot first, when Symbol hasn't been initialized yet. So later I've tried adding some extra code to eliminate the ArgumentNullException so that it can run to the setter of Symbol and then everything goes fine except that the UI doesn't get updated anyway.
Could anyone tell me where I've got wrong?
Thx in advance!!
Why not just use:
private string _symbol;
public string Symbol
{
get { return _symbol;}
set
{
_symbol = value;
NotifyOfPropertyChange(() => Symbol);
NotifyOfPropertyChange(() => Snapshot);
}
}
public StockSnapshot Snapshot
{
get { return Symbol!=null? GlobalData.Current.Snapshots[Symbol]:null; }
}
In this case you don't try and get the data from GlobalData when Symbol is null (sensible approach anyway!) and when "Symbol" is set you call NotifyOfPropertyChange() on Snapshot to force a re-get of the property.

How to call an async method from a getter or setter?

What'd be the most elegant way to call an async method from a getter or setter in C#?
Here's some pseudo-code to help explain myself.
async Task<IEnumerable> MyAsyncMethod()
{
return await DoSomethingAsync();
}
public IEnumerable MyList
{
get
{
//call MyAsyncMethod() here
}
}
There is no technical reason that async properties are not allowed in C#. It was a purposeful design decision, because "asynchronous properties" is an oxymoron.
Properties should return current values; they should not be kicking off background operations.
Usually, when someone wants an "asynchronous property", what they really want is one of these:
An asynchronous method that returns a value. In this case, change the property to an async method.
A value that can be used in data-binding but must be calculated/retrieved asynchronously. In this case, either use an async factory method for the containing object or use an async InitAsync() method. The data-bound value will be default(T) until the value is calculated/retrieved.
A value that is expensive to create, but should be cached for future use. In this case, use AsyncLazy from my blog or AsyncEx library. This will give you an awaitable property.
Update: I cover asynchronous properties in one of my recent "async OOP" blog posts.
You can't call it asynchronously, since there is no asynchronous property support, only async methods. As such, there are two options, both taking advantage of the fact that asynchronous methods in the CTP are really just a method that returns Task<T> or Task:
// Make the property return a Task<T>
public Task<IEnumerable> MyList
{
get
{
// Just call the method
return MyAsyncMethod();
}
}
Or:
// Make the property blocking
public IEnumerable MyList
{
get
{
// Block via .Result
return MyAsyncMethod().Result;
}
}
I really needed the call to originate from the get method, due to my decoupled architecture. So I came up with the following implementation.
Usage: Title is in a ViewModel or an object you could statically declare as a page resource. Bind to it and the value will get populated without blocking the UI, when getTitle() returns.
string _Title;
public string Title
{
get
{
if (_Title == null)
{
Deployment.Current.Dispatcher.InvokeAsync(async () => { Title = await getTitle(); });
}
return _Title;
}
set
{
if (value != _Title)
{
_Title = value;
RaisePropertyChanged("Title");
}
}
}
You can use Task like this :
public int SelectedTab
{
get => selected_tab;
set
{
selected_tab = value;
new Task(async () =>
{
await newTab.ScaleTo(0.8);
}).Start();
}
}
I think that we can await for the value just returning first null and then get the real value, so in the case of Pure MVVM (PCL project for instance) I think the following is the most elegant solution:
private IEnumerable myList;
public IEnumerable MyList
{
get
{
if(myList == null)
InitializeMyList();
return myList;
}
set
{
myList = value;
NotifyPropertyChanged();
}
}
private async void InitializeMyList()
{
MyList = await AzureService.GetMyList();
}
I thought .GetAwaiter().GetResult() was exactly the solution to this problem, no?
eg:
string _Title;
public string Title
{
get
{
if (_Title == null)
{
_Title = getTitle().GetAwaiter().GetResult();
}
return _Title;
}
set
{
if (value != _Title)
{
_Title = value;
RaisePropertyChanged("Title");
}
}
}
Since your "async property" is in a viewmodel, you could use AsyncMVVM:
class MyViewModel : AsyncBindableBase
{
public string Title
{
get
{
return Property.Get(GetTitleAsync);
}
}
private async Task<string> GetTitleAsync()
{
//...
}
}
It will take care of the synchronization context and property change notification for you.
You can create an event and invoke an event when the property is changed.
Something like this:
private event EventHandler<string> AddressChanged;
public YourClassConstructor(){
AddressChanged += GoogleAddressesViewModel_AddressChanged;
}
private async void GoogleAddressesViewModel_AddressChanged(object sender, string e){
... make your async call
}
private string _addressToSearch;
public string AddressToSearch
{
get { return _addressToSearch; }
set
{
_addressToSearch = value;
AddressChanged.Invoke(this, AddressToSearch);
}
}
When I ran into this problem, trying to run an async method synchronicity from either a setter or a constructor got me into a deadlock on the UI thread, and using an event handler required too many changes in the general design.
The solution was, as often is, to just write explicitly what I wanted to happen implicitly, which was to have another thread handle the operation and to get the main thread to wait for it to finish:
string someValue=null;
var t = new Thread(() =>someValue = SomeAsyncMethod().Result);
t.Start();
t.Join();
You could argue that I abuse the framework, but it works.
Necromancing.
In .NET Core/NetStandard2, you can use Nito.AsyncEx.AsyncContext.Run instead of System.Windows.Threading.Dispatcher.InvokeAsync:
class AsyncPropertyTest
{
private static async System.Threading.Tasks.Task<int> GetInt(string text)
{
await System.Threading.Tasks.Task.Delay(2000);
System.Threading.Thread.Sleep(2000);
return int.Parse(text);
}
public static int MyProperty
{
get
{
int x = 0;
// https://stackoverflow.com/questions/6602244/how-to-call-an-async-method-from-a-getter-or-setter
// https://stackoverflow.com/questions/41748335/net-dispatcher-for-net-core
// https://github.com/StephenCleary/AsyncEx
Nito.AsyncEx.AsyncContext.Run(async delegate ()
{
x = await GetInt("123");
});
return x;
}
}
public static void Test()
{
System.Console.WriteLine(System.DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss.fff"));
System.Console.WriteLine(MyProperty);
System.Console.WriteLine(System.DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss.fff"));
}
}
If you simply chose System.Threading.Tasks.Task.Run or System.Threading.Tasks.Task<int>.Run, then it wouldn't work.
I think my example below may follow #Stephen-Cleary 's approach but I wanted to give a coded example. This is for use in a data binding context for example Xamarin.
The constructor of the class - or indeed the setter of another property on which it is dependent - may call an async void that will populate the property on completion of the task without the need for an await or block. When it finally gets a value it will update your UI via the NotifyPropertyChanged mechanism.
I'm not certain about any side effects of calling a aysnc void from a constructor. Perhaps a commenter will elaborate on error handling etc.
class MainPageViewModel : INotifyPropertyChanged
{
IEnumerable myList;
public event PropertyChangedEventHandler PropertyChanged;
public MainPageViewModel()
{
MyAsyncMethod()
}
public IEnumerable MyList
{
set
{
if (myList != value)
{
myList = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("MyList"));
}
}
}
get
{
return myList;
}
}
async void MyAsyncMethod()
{
MyList = await DoSomethingAsync();
}
}
I review all answer but all have a performance issue.
for example in :
string _Title;
public string Title
{
get
{
if (_Title == null)
{
Deployment.Current.Dispatcher.InvokeAsync(async () => { Title = await getTitle(); });
}
return _Title;
}
set
{
if (value != _Title)
{
_Title = value;
RaisePropertyChanged("Title");
}
}
}
Deployment.Current.Dispatcher.InvokeAsync(async () => { Title = await getTitle(); });
use dispatcher which is not a good answer.
but there is a simple solution, just do it:
string _Title;
public string Title
{
get
{
if (_Title == null)
{
Task.Run(()=>
{
_Title = getTitle();
RaisePropertyChanged("Title");
});
return;
}
return _Title;
}
set
{
if (value != _Title)
{
_Title = value;
RaisePropertyChanged("Title");
}
}
}
You can change the proerty to Task<IEnumerable>
and do something like:
get
{
Task<IEnumerable>.Run(async()=>{
return await getMyList();
});
}
and use it like
await MyList;

Categories

Resources