Currently my RadDatagrid1 has a Cell_click action for the RadDatagrid1, and when a ClientName is selected, that client info is projected in DataGrid2.
code within Mouse Double Click:
private void Cell_click(object sender, GridViewSelectedCellsChangedEventArgs e)
{
Var Details = (from info in contacts
where info.ClientName = sender.CurrentCell.ToString()
select new {info.ClientName, info.ClientAddress, Info.ClientNumber});
DataGrid2.ItemsSource = Details.ToList();
}
This is currently what i have but, it should be a reactive UI.
An example of reactitve UI i was told to look at was this in the GridViewModel:
this.WhenAny(x => x.Forename, x => x.Surname, x => x.City, (p1, p2, p3) => Unit.Default).Subscribe(x => Filter());
But that doesn't quite make sense to me. If I could get guidance and tips how to convert this to reactive UI please.
I am a newbie to Reactive UI and my experience so far has been through trial and error, due to the lack of documentation. So my method below might not be correct.
Make sure you have a ViewModel backing your WPF control (see this page)
Your ViewModel should look something like:
public class ViewModel : ReactiveObject {
// ClientInfo type is the type of object you want to bind to the DataGrid
private ClientInfo clientInfo;
public ClientInfo ClientInfo {
set { this.RaiseAndSetIfChanged(ref clientInfo, value); }
get { return clientInfo; }
}
// Move contacts IEnumerable/IQueryable to your ViewModel
private IQueryable<ClientInfo> contacts;
public LoadInfo(string clientName) {
ClientInfo = (from info in contacts
where info.ClientName = clientName
select new {info.ClientName, info.ClientAddress, Info.ClientNumber})
}
}
Make sure your View (the control class) implements IViewFor<T> where T is the type of your View Model. Bind views according to the documentation here.
Do something like this for your View:
// Implement the methods on that interface, which I will not include below
public partial class View : IViewFor<ViewModel> {
private ICommand loadClientInfo;
public View() { // constructor
InitializeComponent(); // Don't forget this
// Binds the data in your ViewModel with the ItemSource of your DataGrid
this.OneWayBind(ViewModel, vm => vm.ClientInfo, x => x.DataGrid2.ItemSource);
}
private void Cell_click(object sender, GridViewSelectedCellsChangedEventArgs e)
{
ViewModel.LoadInfo(sender.CurrentCell.ToString());
}
}
Related
I have created ChatMessageGroup and ChatMessageGroupCollection and a ListView with ItemsSource set to CollectionViewSource:
<ListView x:Name="ChatMessageLv" ItemsSource="{Binding SelectedChat.ChatMessageGroupCollection.Cvs.View}" ItemTemplateSelector="{StaticResource ChatMessageDataTemplateSelector}">
public class ChatMessageGroup : IGrouping<DateTime, ChatMessage>, INotifyCollectionChanged
{
private ObservableCollection<ChatMessage> _chatMessages;
public DateTime Key { get; set; }
public ObservableCollection<ChatMessage> ChatMessages
{
get { return _chatMessages; }
set
{
if (_chatMessages != null)
_chatMessages.CollectionChanged -= CollectionChanged;
_chatMessages = value;
_chatMessages.CollectionChanged += CollectionChanged;
}
}
public ChatMessageGroup()
{
ChatMessages = new ObservableCollection<ChatMessage>();
}
public IEnumerator<ChatMessage> GetEnumerator()
{
return ChatMessages.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public event NotifyCollectionChangedEventHandler CollectionChanged;
}
public class ChatMessageGroupCollection : IEnumerable<ChatMessageGroup>
{
private readonly ObservableCollection<ChatMessageGroup> _groups;
public ObservableCollection<ChatMessage> Source { get; set; }
public CollectionViewSource Cvs { get; set; }
public ChatMessageGroupCollection(ObservableCollection<ChatMessage> messages)
{
Source = messages;
messages.CollectionChanged += Messages_CollectionChanged;
var groups = messages
.GroupBy(GetGroupKey)
.Select(x => new ChatMessageGroup()
{
Key = x.Key,
ChatMessages = x.OrderBy(GetGroupKey).ToObservableOrDefault()
})
.OrderBy(x => x.Key);
_groups = new ObservableCollection<ChatMessageGroup>(groups);
Cvs = new CollectionViewSource() { IsSourceGrouped = true, Source = _groups };
}
...
Everything works fine in here except the changes inside group collection:
_groups.Add(new ChatMessageGroup()); -> this line reflect changes in ListView
but if I do like this: _groups[0].ChatMessages.Add(new ChatMessage()) it doesn't work even though ChatMessageGroup is implementing INotifyCollectionChanged and is raised every time ChatMessages ObservableCollection is changed.
The workaround is to update ChatMessages and remove group from _groups and then add it again but it's not a solution. Refresh() on CollectionViewSource is not available in UWP. Are there any other solutions?
Whilst this doesn't technically qualify as an answer to the question I do think it might qualify as an architectural answer.
The way to make a grouped list view update based on the underlying collection changing in WPF is as simple as setting IsLiveGroupingRequested to true on the CollectionViewSource instance declared in XAML.
As I've been working my way through UWP (after nearly a decade of WPF) I've come to the conclusion that Microsoft are suggesting through omission that this isn't the right approach to the problem for UWP. So going to the lengths of implementing the feature yourself could be construed as missing the point somewhat.
In my particular situation I've decided to change my approach entirely and implement the rendering as multiple instance of ListViews as opposed to forcing an old paradigm onto a new platform.
The result of this actually made me arrive at a solution that improved my UX to boot.
Food for thought ...
I am trying to make a call to a wcf service with my silverlight application and I am having some trouble understanding how the model returns the result back to the view model. Within my view model I have the following command:
public DelegateCommand GetSearchResultCommand
{
get
{
if (this._getSearchResultCommand == null)
this._getSearchResultCommand = new DelegateCommand(GetSearchResultCommandExecute, CanGetSearchResultsCommandExecute);
return this._getSearchResultCommand;
}
}
private void GetSearchResultCommandExecute(object parameter)
{
this.SearchResults = this._DataModel.GetSearchResults(this.SearchTerm);
}
/// <summary>
/// Bindable property for SearchResults
/// </summary>
public ObservableCollection<QueryResponse> SearchResults
{
get
{
return this._SearchResults;
}
private set
{
if (this._SearchResults == value)
return;
// Set the new value and notify
this._SearchResults = value;
this.NotifyPropertyChanged("SearchResults");
}
}
then within my model I have the following code
public ObservableCollection<QueryResponse> GetSearchResults(string searchQuery)
{
//return type cannot be void needs to be a collection
SearchClient sc = new SearchClient();
//******
//TODO: stubbed in placeholder for Endpoint Address used to retreive proxy address at runtime
// sc.Endpoint.Address = (clientProxy);
//******
sc.QueryCompleted += new EventHandler<QueryCompletedEventArgs>(sc_QueryCompleted);
sc.QueryAsync(new Query { QueryText = searchQuery });
return LastSearchResults;
}
void sc_QueryCompleted(object sender, QueryCompletedEventArgs e)
{
ObservableCollection<QueryResponse> results = new ObservableCollection<QueryResponse>();
results.Add(e.Result);
this.LastSearchResults = results;
}
When I insert breakpoints within the model I see where the query is being executed and a result is returned within the model (this.LastSearchResults = results) however I cannot seem to get this collection to update/ notify the view model of the result. I've generated and run a similar test using just a method and dummy class and it seems to work so I suspect the issue is due to the async call /threading. I have INotifyPropertyChanged within the ViewModel to sync the View and ViewModel. Do I need to also implement INotifyPropChng within the model as well? I'm new to mvvm so any help / example of how I should approach this would be appreciated.
Thank you,
UPDATE
In further testing I added INotifyPropertyChanged to the model and changed the Completed event as follows:
void sc_QueryCompleted(object sender, QueryCompletedEventArgs e)
{
ObservableCollection<QueryResponse> results = new ObservableCollection<QueryResponse>();
results.Add(e.Result);
//this.LastSearchResults = results;
SearchResults = results;
}
Placing a watch on Search Results I now see it is updated with results from teh WCF. My question is still around is this teh correct approach? It seems to work right now however I am curious if I am missing something else or if I should not be placing INotify within the Model.
Thank you,
I've found that it's best to encapsulate my WCF services in an additional layer of Service classes. This allows me to more easily Unit Test my ViewModels. There are several patterns when doing this, though this is the simplest I've used. The pattern is to create a method that matches the definition of the service call, though also contains an Action that can be invoked after the service call completes.
public class Service : IService
{
public void GetSearchResults(string searchQuery, Action<ObservableCollection<QueryResponse>> reply)
{
//return type cannot be void needs to be a collection
SearchClient sc = new SearchClient();
//******
//TODO: stubbed in placeholder for Endpoint Address used to retreive proxy address at runtime
// sc.Endpoint.Address = (clientProxy);
//******
sc.QueryCompleted += (s,e) =>
{
ObservableCollection<QueryResponse> results = new ObservableCollection<QueryResponse>();
results.Add(e.Result);
reply(results);
};
sc.QueryAsync(new Query { QueryText = searchQuery });
}
}
You can also provide an interface that your ViewModel can use. This makes Unit Testing even easier, though is optional.
public interface IService
{
void GetSearchResults(string searchQuery, Action<ObservableCollection<QueryResponse>> reply);
}
Your ViewModel would then look something like this:
public class MyViewModel : INotifyPropertyChanged
{
private IService _service;
public MyViewModel()
: this(new Service())
{ }
public MyViewModel(IService service)
{
_service = service;
SearchResults = new ObservableCollection<QueryResponse>();
}
private ObservableCollection<QueryResponse> _searchResults
public ObservableCollection<QueryResponse> SearchResults
{
get { return _searchResults; }
set
{
_searchResults = value;
NotifyPropertyChanged("SearchResults");
}
}
public void Search()
{
_service.GetSearchResults("abcd", results =>
{
SearchResults.AddRange(results);
});
}
protected void NotifyPropertyChanged(string property)
{
var handler = this.PropertyChanged;
if(handler != null)
handler(new PropertyChangedEventArgs(property));
}
}
An additional reason for encapsulating your service calls into another class like this is that it can provide a single place for such things as logging and error handling. That way your ViewModel itself doesn't need to take care of those things specifically related to the Service.
I would likely use something along the lines of:
public class ViewModel : INotifyPropertyChanged
{
private readonly IModel model;
private readonly DelegateCommand getSearchResultsCommand;
public DelegateCommand GetSearchResultsCommand
{
get { return getSearchResultsCommand; }
}
public ObservableCollection<QueryResponse> SearchResults
{
get { return model.SearchResults; }
}
public ViewModel(IModel model)
{
this.model = model;
this.model.SearchResultsRetrieved += new EventHandler(model_SearchResultsRetrieved);
this.getSearchResultsCommand = new DelegateCommand(model.GetSearchResultCommandExecute, model.CanGetSearchResultsCommandExecute);
}
private void model_SearchResultsRetrieved(object sender, EventArgs e)
{
this.NotifyPropertyChanged("SearchResults");
}
}
public interface IModel
{
event EventHandler SearchResultsRetrieved;
void GetSearchResultCommandExecute(object parameter);
bool CanGetSearchResultsCommandExecute(object parameter);
ObservableCollection<QueryResponse> SearchResults { get; }
}
With the SearchResultsRetrieved event being fired by the Model when its SearchResults collection has been filled with the appropriate data. I prefer to have custom events rather than implement INotifyPropertyChanged on my models, particularly if there are only one, or a few, events that need to be communicated to the viewmodel.
I have an ItemType that is coming from EF. This ItemType is wrapped in a ItemTypeViewModel. Many ItemTypes are wrapped in ItemTypeViewModels and are being put in a ObservableCollection in the ViewModel for the user control that will display them:
I use the CollectionView so I can page through them. The screen looks like this:
Now I'm thinking that the buttons that are used for paging that are in the user control could better be placed in the Window that will contain the user control. So, in my user control I know have commands like this:
But I want them to be in the window. I don't know if this will be good design, but if I will go through with this, how to relay the commands from the window to the usercontrol?
Another question I have is how to fill the combobox in the user control. They will always have the same values, but the selected item will change per ItemType.
I know two ways how to do this.
1) Add new class, for example, MainWindowViewModel and add there 2 commands and an instance of UserControlViewModel (you haven't said the title, so I will call it in this way). Here is a part of example:
public class MainWindowViewModel
{
public UserControlViewModel ChildControlViewModel { get; set; }
private Lazy<RelayCommand> nextCommand = new Lazy<RelayCommand>(() =>
new RelayCommand(
() => this.ChildControlViewModel.CollectionView.MoveCurrentToNext(),
() => this.ChildControlViewModel.CollectionView.CurrentPosition < this.ChildControlViewModel.ItemTypes.Count - 1));
public ICommand NextCommand
{
get { return nextCommand.Value; }
}
//prev command...
}
I have used the Lazy class, but the main idea is clear: the code is the same, except the call this.ChildControlViewModel.CollectionView instead of CollectionView.
2) Use the Messenger class.
This way isn't so obvious and it has only one advantage: the viewmodels are loosely connected.
public class MainWindowViewModel
{
public const string NextCommandNotification = "NextCommand";
public const string PreviousCommandNotification = "PreviousCommand";
private bool isNextCommandEnabled;
private bool isPreviousCommandEnabled;
public MainWindowViewModel()
{
this.NextCommand = new RelayCommand(
() => Messenger.Default.Send(new NotificationMessage<MainWindowViewModel>(this, NextCommandNotification)),
() => this.isNextCommandEnabled);
//prev command...
Messenger.Default.Register<NotificationMessage<UserControlViewModel>>(this,
msg =>
{
if (msg.Notification == UserControlViewModel.CurrentItemChangedNotification)
{
this.isNextCommandEnabled = msg.Content.CollectionView.CurrentPosition < msg.Content.ItemTypes.Count - 1;
this.NextCommand.RaiseCanExecuteChanged();
//prev command...
}
});
}
public ICommand NextCommand { get; private set; }
//prev command...
}
public class UserControlViewModel
{
public const string CurrentItemChangedNotification = "CurrentItemChanged";
public UserControlViewModel()
{
Messenger.Default.Register<NotificationMessage<MainWindowViewModel>>(this,
msg =>
{
if (msg.Notification == MainWindowViewModel.NextCommandNotification)
this.CollectionView.MoveCurrentToNext();
else if (msg.Notification == MainWindowViewModel.PreviousCommandNotification)
this.CollectionView.MoveCurrentToPrevious();
});
this.CollectionView.CurrentChanged += (s,e) => Messenger.Default.Send(new NotificationMessage<UserControlViewModel>(this, CurrentItemChangedNotification))
}
}
I'm not sure whether this code will work correctly. And it is not easy to explain.
The MainWindowViewModel class send the message when a user press the button. The UserControlViewModel class process the message, change the position of the current item, and send the CurrentItemChangedNotification message. The MainWindowViewModel class process this message and updates the CanExecute part of the command.
1st solution is better for me, but at the same time I use the Messenger class quite often. It depends on the situation.
I have a need of one DependencyProperty from a View in my ViewModel constructor:
My problem: MEF wouldn't SatisfyImports() 'because it is marked with one or more ExportAttributes' (that is the exception)
This is the code structure for the VIEW:
public class MyView : UserControl
{
[Export(MethodTypes.ChartType)]
public Charts MyChartType
{
get
{
object k = GetValue(ChartTypeProperty);
Charts f = (Charts)Enum.Parse(typeof(Charts), k.ToString(), true);
return f;
}
set
{
SetValue(ChartTypeProperty, value);
}
}
[Import(ViewModelTypes.GenericChartViewModel)]
public object ViewModel
{
set
{
DataContext = value;
}
}
public MyView()
{
InitializeComponent();
if (!ViewModelBase.IsInDesignModeStatic)
{
// Use MEF To load the View Model
CompositionInitializer.SatisfyImports(this);
}
}
}
and the VIEWMODEL:
[PartCreationPolicy(CreationPolicy.NonShared)]
[Export(ViewModelTypes.GenericChartViewModel)]
public class GenericChartViewModel
{
[ImportingConstructor]
public GenericChartViewModel([Import(MethodTypes.ChartType)] Charts forChartType)
{
string test = forChartType.ToString();
}
}
Please give me any hints on this or maybe suggest a better solution for passing parameters through mef
In my case, I would need to pass only dependecyproperty's for now...
Thanks
Your work around isn't really good.. can't you remove the export from ChartTypes and pass it manually to whoever wants it? I presume the viewmodel is only one insterested in it..
I managed to put this through !
Instead of the code in the default constructor, I use:
void MyView_Loaded(object sender, RoutedEventArgs e)
{
if (!ViewModelBase.IsInDesignModeStatic)
{
var catalog = new TypeCatalog(typeof(GenericChartViewModel));
var container = new CompositionContainer(catalog);
container.ComposeParts(this);
}
}
and the dependencyproperty value is correctly propagated to the ViewModel
(must do this after control is loaded, or the property will have its default value)
However, I would be very grateful if someone could:
tell me how generate a catalog from another non-referenced assembly?
Thanks
I have an Image control with it's source bound to a property on an object(string url to an image). After making a service call, i update the data object with a new URL. The exception is thrown after it leaves my code, after invoking the PropertyChanged event.
The data structure and the service logic are all done in a core dll that has no knowledge of the UI. How do I sync up with the UI thread when i cant access a Dispatcher?
PS: Accessing Application.Current.RootVisual in order to get at a Dispatcher is not a solution because the root visual is on a different thread(causing the exact exception i need to prevent).
PPS: This only is a problem with the image control, binding to any other ui element, the cross thread issue is handled for you.
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => {...});
Also look here.
Have you tried implementing INotifyPropertyChanged?
The property getter for RootVisual on the Application class has a thread check which causes that exception. I got around this by storing the root visual's dispatcher in my own property in my App.xaml.cs:
public static Dispatcher RootVisualDispatcher { get; set; }
private void Application_Startup(object sender, StartupEventArgs e)
{
this.RootVisual = new Page();
RootVisualDispatcher = RootVisual.Dispatcher;
}
If you then call BeginInvoke on App.RootVisualDispatcher rather than Application.Current.RootVisual.Dispatcher you shouldn't get this exception.
I ran into a similar issue to this, but this was in windows forms:
I have a class that has it's own thread, updating statistics about another process, there is a control in my UI that is databound to this object. I was running into cross-thread call issues, here is how I resolved it:
Form m_MainWindow; //Reference to the main window of my application
protected virtual void OnPropertyChanged(string propertyName)
{
if(PropertyChanged != null)
if(m_MainWindow.InvokeRequired)
m_MainWindow.Invoke(
PropertyChanged, this, new PropertyChangedEventArgs(propertyName);
else
PropertyChanged(this, new PropertyChangedEventArgs(propertyName);
}
This seems to work great, if anyone has suggestions, please let me know.
When ever we want to update UI related items that action should happen in the UI thread else you will get an invalid cross thread access exception
Deployment.Current.Dispatcher.BeginInvoke( () =>
{
UpdateUI(); // DO the actions in the function Update UI
});
public void UpdateUI()
{
//to do :Update UI elements here
}
The INotifyPropertyChanged interface is used to notify clients, typically binding clients, that a property value has changed.
For example, consider a Person object with a property called FirstName. To provide generic property-change notification, the Person type implements the INotifyPropertyChanged interface and raises a PropertyChanged event when FirstName is changed.
For change notification to occur in a binding between a bound client and a data source, your bound type should either:
Implement the INotifyPropertyChanged interface (preferred).
Provide a change event for each property of the bound type.
Do not do both.
Example:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Runtime.CompilerServices;
using System.Windows.Forms;
// Change the namespace to the project name.
namespace TestNotifyPropertyChangedCS
{
// This form demonstrates using a BindingSource to bind
// a list to a DataGridView control. The list does not
// raise change notifications. However the DemoCustomer type
// in the list does.
public partial class Form1 : Form
{
// This button causes the value of a list element to be changed.
private Button changeItemBtn = new Button();
// This DataGridView control displays the contents of the list.
private DataGridView customersDataGridView = new DataGridView();
// This BindingSource binds the list to the DataGridView control.
private BindingSource customersBindingSource = new BindingSource();
public Form1()
{
InitializeComponent();
// Set up the "Change Item" button.
this.changeItemBtn.Text = "Change Item";
this.changeItemBtn.Dock = DockStyle.Bottom;
this.changeItemBtn.Click +=
new EventHandler(changeItemBtn_Click);
this.Controls.Add(this.changeItemBtn);
// Set up the DataGridView.
customersDataGridView.Dock = DockStyle.Top;
this.Controls.Add(customersDataGridView);
this.Size = new Size(400, 200);
}
private void Form1_Load(object sender, EventArgs e)
{
// Create and populate the list of DemoCustomer objects
// which will supply data to the DataGridView.
BindingList<DemoCustomer> customerList = new BindingList<DemoCustomer>();
customerList.Add(DemoCustomer.CreateNewCustomer());
customerList.Add(DemoCustomer.CreateNewCustomer());
customerList.Add(DemoCustomer.CreateNewCustomer());
// Bind the list to the BindingSource.
this.customersBindingSource.DataSource = customerList;
// Attach the BindingSource to the DataGridView.
this.customersDataGridView.DataSource =
this.customersBindingSource;
}
// Change the value of the CompanyName property for the first
// item in the list when the "Change Item" button is clicked.
void changeItemBtn_Click(object sender, EventArgs e)
{
// Get a reference to the list from the BindingSource.
BindingList<DemoCustomer> customerList =
this.customersBindingSource.DataSource as BindingList<DemoCustomer>;
// Change the value of the CompanyName property for the
// first item in the list.
customerList[0].CustomerName = "Tailspin Toys";
customerList[0].PhoneNumber = "(708)555-0150";
}
}
// This is a simple customer class that
// implements the IPropertyChange interface.
public class DemoCustomer : INotifyPropertyChanged
{
// These fields hold the values for the public properties.
private Guid idValue = Guid.NewGuid();
private string customerNameValue = String.Empty;
private string phoneNumberValue = String.Empty;
public event PropertyChangedEventHandler PropertyChanged;
// This method is called by the Set accessor of each property.
// The CallerMemberName attribute that is applied to the optional propertyName
// parameter causes the property name of the caller to be substituted as an argument.
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
// The constructor is private to enforce the factory pattern.
private DemoCustomer()
{
customerNameValue = "Customer";
phoneNumberValue = "(312)555-0100";
}
// This is the public factory method.
public static DemoCustomer CreateNewCustomer()
{
return new DemoCustomer();
}
// This property represents an ID, suitable
// for use as a primary key in a database.
public Guid ID
{
get
{
return this.idValue;
}
}
public string CustomerName
{
get
{
return this.customerNameValue;
}
set
{
if (value != this.customerNameValue)
{
this.customerNameValue = value;
NotifyPropertyChanged();
}
}
}
public string PhoneNumber
{
get
{
return this.phoneNumberValue;
}
set
{
if (value != this.phoneNumberValue)
{
this.phoneNumberValue = value;
NotifyPropertyChanged();
}
}
}
}
}