I have events I'm trying to display in a listview the events come to me like this
public class EventRecord
{
public uint EventCode{get;}
public DateTime DateTime{get;}
//....
}
I created an ObservableCollection<EventRecord> and bound my listView.ItemSource to it. The problem is I want to display strings that are contained in a seperate collection. Something like this
private Dictionary<uint,EventMessages> messages;
private ObservableCollection<EventRecord> log;
messages[log.EventCode].Description <--- How to bind to this
I also need to display the DateTime and some other stuff
Thanks
Related
I need to present an object differently, twice.
as a node in a TreeView (navigation/rename)
as 2 TextBoxes (rename/edit content)
public class Item
{
public string Name{get;set;}
public string Content{get;set;}
}
My first solution was to keep things simple:
public class MainViewModel
{
// collection of items (treeview navigation)
public BindingList<ItemViewModel> Items{get;set;}
// selected item (from treeview navigation)
// used for textbox edit
public ItemViewModel SelectedItem{get;set;}
}
public class ItemViewModel
{
// Used for treeview navigation
public bool IsSelected{get;set;}
public bool IsExpanded{get;set;}
public bool IsInEditNameMode{get;set;}
public BindingList<ItemViewModel> Children{get;set;}
public void BuildChildren();
// Used for treeview display/rename
// Used for textbox display/rename
public string Name{get;set;}
// Used for textbox edit
public string Content{get;set;}
}
This works well for a while.
But as the application grows more complex, the view model gets "polluted" more and more.
For example, adding additional presentations for the same view model (Advanced properties, Graph representation, etc)
public class ItemViewModel
{
// Used for Advanced properties
public BindingList<PropertyEntry> Properties {get;set;}
public PropertyEntry SelectedProperty{get;set;}
// Used for graph relationship
public BindingList<ItemViewModel> GraphSiblings{get;set;}
public bool IsGraphInEditNameMode{get;set;}
public bool IsSelectedGraphNode {get;set;}
public void BuildGraphSiblings();
// Used for treeview navigation
public bool IsNavigationInEditNameMode{get;set;}
public bool IsSelectedNavigationNode{get;set;}
public bool IsExpandedNavigationNode{get;set;}
public BindingList<ItemViewModel> NavigationChildren{get;set;}
public void BuildNavigationChildren();
// Used for treeview display/rename
// Used for textbox display/rename
// Used for graph display
// Used for Advanced properties display
public string Name{get;set;}
// Used for textbox edit
public string Content{get;set;}
}
Currently, I'm still using a single view model for multiple presentations, because it keeps the selected item in-sync across all presentation.
Also, I do not have to keep duplicating properties (Name/Content).
And finally, PropertyChanged notification helps updates all presentation of the item (ie, changing Name in navigation updates TextBox/Graph/Advanced properties/etc).
However, it also feels like a violation of several principles (single responsibility, least privilege, etc).
But I'm not quite sure how to refactor it, without writing a lot of code to keep the sync/property notification working/duplicating the model's properties across each new view model/etc)
What I would like to know:
If it were up to you, how would you have solved this?
At the moment, everything is still working. I just feel like the code could be further improved, and that's what I need help with.
How about using inheritance? Have a basic ItemViewModel, then subclass it to create a TreeViewItemViewModel, where you add the properties that relate to the tree-view rendering of this item within the subclass.
Could we,
try separating-out various view-specific-behaviors from the ItemViewModel class.
place/encapsulate the view-specific-behaviors in separate class (Behavior classes).
This gives you flexibility at run-time to instantiate/inject/switch behaviors.
Yes, try to use Strategy pattern for making a cleaner, single responsible, easy to maintain code.
I am working on my first WPF/MVVM application, and I have come across a limitation in my knowledge of commands!
Here is my scenario.
I have a window - Customer.xaml.
It houses 2 usercontrols
viewCustomerSearch.xaml
viewCustomerDetails.xaml
Each of THOSE has it's own view model.
So, the hierarchy looks like this:
... Customer.xaml
... ... viewCustomerSearch.xaml
... ... ... viewmodelCustomerSearch.xaml
... ... viewCustomerDetails.xaml
... ... ... viewmodelCustomerDetails.xaml
I understand this to be a 'not uncommon' scenario.
For what it is worth, the user selects a customer by double clicking on a listview line in the viewCustomerSearch.xaml control.
The problem is: I now need to tell the viewmodelCustomerDetails.xaml class which customer the user has just selected. I cannot work this out at all.
Does anyone have any help on where I declare the command I need, how it gets hooked up, where the implementation code fires, etc?
Any help gratefully appreciated,
DS
Typically, to do inter-viewmodel communication, you can either:
Use standard .NET events, and use the parent view model as the mediator - in your case the Customer view model would have references to the 2 child view models, and can subscribe to events, and call appropriate methods on the child view models when the events are published
Use an event aggregator pattern
Frameworks such as Caliburn.Micro and Prism provide an implementation of the event aggregator pattern.
Alternatively, if you don't need completely decoupled view-models, then your Customers.xaml could set its DataContext to an instance of CustomersViewModel. The search view would inherit this data context, would bind it's list view to the list of customers, and would set the SelectedItem property in response to a double click. The detail view DataContext would be bound to the SelectedItem property.
public class CustomersViewModel : ViewModelBase
{
public Customer SelectedItem
{
get { return _selectedItem; }
set { Set(() => SelectedItem, ref _selectedItem, value); }
}
private Customer _selectedItem;
public IEnumerable<Customer> Customers { get; private set; }
}
public class Customer : ViewModelBase
{
private string _name;
public string Name
{
get { return _name; }
set { Set(() => Name, ref _name, value); }
}
...
}
MVVM pattern is implemented in my Silverlight4 application.
Originally, I worked with ObservableCollection of objects in my ViewModel:
public class SquadViewModel : ViewModelBase<ISquadModel>
{
public SquadViewModel(...) : base(...)
{
SquadPlayers = new ObservableCollection<SquadPlayerViewModel>();
...
_model.DataReceivedEvent += _model_DataReceivedEvent;
_model.RequestData(...);
}
private void _model_DataReceivedEvent(ObservableCollection<TeamPlayerData> allReadyPlayers, ...)
{
foreach (TeamPlayerData tpd in allReadyPlayers)
{
SquadPlayerViewModel sp = new SquadPlayerViewModel(...);
SquadPlayers.Add(sp);
}
}
...
}
Here is a peacie of XAML code for grid displaying:
xmlns:DataControls="clr-namespace:System.Windows.Controls;
assembly=System.Windows.Controls.Data"
...
<DataControls:DataGrid ItemsSource="{Binding SquadPlayers}">
...</DataControls:DataGrid>
and my ViewModel is bound to DataContext property of the view.
This collection (SquadPlayers) is not changed after its creation so I would like to change its type to
List<SquadPlayerViewModel>
. When I did that, I also added
RaisePropertyChanged("SquadPlayers")
in the end of '_model_DataReceivedEvent' method (to notify the grid that list data are changed.
The problem is that on initial displaying grid doesn't show any record... Only when I click on any column header it will do 'sorting' and display all items from the list...
Question1: Why datagrid doesn't contain items initially?
Q2: How to make them displayed automatically?
Thanks.
P.S. Here is a declaration of the new List object in my view-model:
public List<SquadPlayerViewModel> SquadPlayers { get; set; }
You can't use List as a binding source, because List not implement INotifyCollectionChanged it is require for WPF/Silverlight to have knowledge for whether the content of collection is change or not. WPF/Sivlerlight than can take further action.
I don't know why you need List<> on your view model, but If for abstraction reason you can use IList<> instead. but make sure you put instance of ObservableCollection<> on it, not the List<>. No matter what Type you used in your ViewModel Binding Only care about runtime type.
so your code should like this:
//Your declaration
public IList<SquadPlayerViewModel> SquadPlayers { get; set; }
//in your implementation for WPF/Silverlight you should do
SquadPlayers = new ObservableCollection<SquadPlayerViewModel>();
//but for other reason (for non WPF binding) you can do
SquadPlayers = new List<SquadPlayerViewModel>();
I usually used this approach to abstract my "Proxied" Domain Model that returned by NHibernate.
You'll need to have your SquadPlayers List defined something like this:
private ObservableCollection<SquadPlayerViewModel> _SquadPlayers;
public ObservableCollection<SquadPlayerViewModel> SquadPlayers
{
get
{
return _SquadPlayers;
}
set
{
if (_SquadPlayers== value)
{
return;
}
_SquadPlayers= value;
// Update bindings, no broadcast
RaisePropertyChanged("SquadPlayers");
}
}
The problem is that whilst the PropertyChanged event informs the binding of a "change" the value hasn't actually changed, the collection object is still the same object. Some controls save themselves some percieved unnecessary work if they believe the value hasn't really changed.
Try creating a new instance of the ObservableCollection and assigning to the property. In that case the currently assigned object will differ from the new one you create when data is available.
I have a class that contains data from some model. This class has metadata along with the actual value.
class ServerValue {
public int SomeId {get;}
public int SomeOtherId {get;}
public DateTime LastChanged {get;}
public object Value {get;set;}
// this lets me show the value, but how do i update it from the grid?
public override string ToString(){
return Value.ToString();
}
}
Now I also have a class MyDataTable that derives from DataTable that has all kind of logic. It calls the server, gets a bunch of ServerValues and puts them into Rows and Columns.
Finally I have a WPF DataGrid that I bind to the MyDataTable and the data are displayed, because the DataGrid calls ToString on each ServerValue and gets back the value for display. Hurray so far.
Now, I want to have two way databinding, so input on the grid is written back to the ServerValue. So I want to bind the grid cells to the Value property of the ServerValue instead of the ServerValue itself.
Right now the ServerValue of the DataGrid cell is just replaced with a string. I could work around this and all but I'd to try the elegant route first.
So I have a datatable with a complex type in cells and i want two-way databinding to a specific property of that type.
Is this possible? I've been googling on this and i can't anything on this.
Thanks in advance,
John
What you want is a way to convert back and forth from your object to their text reprenstations.
Define a Converter for your Binding
http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx
I have a scenario where i load an ICollectionView in a datagrid.
In some cases I modify the data where the collectionview gets it's data from. If I then reload the grid with configGrid.ItemsSource = configData; for example, the data gets updated.
Now the thing is, I sometimes open a new window using:
var newWindow = new Edit(movie);
newWindow.Show();
The thing is, I also edit the data using this new window. Now I want the datagrid in the first window to be refreshed after I close this second window (actually, it doesn't matter when it gets refreshed, as long as it does).
How do I do this?
I might be missing something here (I have a crippling hangover unfortunately) but can't you handle the window closed event of newWindow and refresh confiGrids itemsource there?
Window newWindow = new Window();
newWindow.Closed += new EventHandler(newWindow_Closed);
newWindow.Show();
void newWindow_Closed(object sender, EventArgs e)
{
configGrid.ItemsSource = configData;
}
If the collection behind the ICollectionView supports INotifyCollectionChanged (like ObservableCollection) and the object itself supports INotifyPropertyChanged then the grid is supposed to update automatically
Otherwise you are on your own and the editing window should raise some sort of notification (maybe an event) that you should receive and update the list.
Ok, here's the long version:
WPF data-binding can update the UI automatically - but it needs to know that something changed in order to trigger the update, the easiest way to do this is to support INotifyPropertyChanged, let's create simple class:
public class Movie
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
}
Now, let's add INotifyPropertyChanged support:
public class Movie : INotifyPropertyChanged
{
public event PropertyChanged;
protected virtual OnPropertyChanged(string property)
{
var ev = PropertyChanged;
if(ev!=null)
{
ev(this, new PropertyChangedEventArgs(property));
}
}
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
OnPropertyChanged("Name");
}
}
}
Now when you bind to the movie class and change the Name property the UI will be updated automatically.
The next step is to handle a list of Movie objects, we do that by using a collection class the implements INotifyCollectionChanged, luckily for us there's one already written in the framework called ObservableCollection, you user ObservableCollection<T> the same way you would use a List<T>.
So, just bind to ObservableCollection and WPF will automatically detect when objects change or when they are added or removed.
ICollectionView is very useful, it adds support for current item, sorting, filtering and grouping on top of the real collection, if that collection is an ObservableCollection everything will just work, so the code:
ObservableCollection<Movie> movies = new ObservableCollection<Movie>();
ICollectionView view = CollectionViewSource.GetDefaultView(movies);
will give you a collection view that supports automatic change notifications.