How to pass parameter to ComboBox ItemsSource binding? - wpf

I am working with WPF for the first time, so please bear with me.
I have a combobox, which is meant to generically display some lookup data. The models for the different types of lookups are exactly the same, just different data sources which are retrieved via a single method call passing different enumerations to control the returned data set. Fairly simple stuff.
public sealed class MyDataProvider
{
public enum Types
{
Green,
Blue,
Orange
}
private readonly ConcurrentDictionary<string, ObservableCollection<LookUpVm>> _lookupData =
new ConcurrentDictionary<string, ObservableCollection<LookUpVm>>();
private static readonly Lazy<MyDataProvider> lazy =
new Lazy<MyDataProvider>(() => new MyDataProvider());
public static MyDataProvider Instance => lazy.Value;
private MyDataProvider()
{
}
public ObservableCollection<LookUpVm> GreenLookupDataSource => GetLookupDataSource(Types.Green);
public ObservableCollection<LookUpVm> GetLookupDataSource(Types lookupEnum)
{
ObservableCollection<LookUpVm> lookupDataSource;
if (_lookupData.TryGetValue(lookupEnum, out lookupDataSource))
return lookupDataSource;
lookupDataSource = new ObservableCollection<LookUpVm>();
var returnedlookupDataSource =
SomeMasterSource.GetlookupDataSourceBylookupEnum(lookupEnum).OrderBy(ia => ia.Name);
foreach (var returnedLookupData in returnedlookupDataSource)
{
lookupDataSource.Add(returnedLookupData);
}
_lookupData.TryAdd(lookupEnum, lookupDataSource);
return lookupDataSource;
}
}
This works great for the 0th iteration, where I create a GreenLookupComboBox.
<ComboBox ItemsSource="{Binding Source={x:Static objectDataProviders:MyDataProvider.Instance},
Path=GreenLookupDataSource}" />
However, what I really need to be able to do is to set up a combobox which can have its Types enum value set on the parent View, which would then call directly to the GetLookupDataSource and pass the enum. We have several dozen lookup types, and defining a new property for each feels less than ideal. Something like the below for the control view...
<ComboBox ItemsSource="{Binding Source={x:Static objectDataProviders:MyDataProvider.Instance},
Path=GetLookupDataSource}" />
And something like the below for where I use the lookup control.
<local:MyLookupControl Type=Types.Green />
Is this even possible?
EDIT:
Here's an example of what I'm trying to accomplish.
I have two key-value pairs of lists.
ListOne
1 - A
2 - B
3 - C
and
ListTwo
1 - X
2 - Y
3 - Z
They are accessible by calling the method GetList(Enum.LookupType). They share the same ViewModel and View. However, I need to place both of them on a form for my users to select from.
I'm looking for some way to use XAML like the following on the View they appear on.
<local:MyLookupControl Method=GetList Parameter=Enum.ListOne/>
<local:MyLookupControl Method=GetList Parameter=Enum.ListTwo />
This should display a pair of comboboxes, one bound to ListOne and one bound to ListTwo.

You're essentially just trying to set up databinding on a couple controls. This is simple then so long as you have the correct datacontext for the view.
Controls can be bound to properties (which is exactly what you are looking for).
Using your edited example here is how you would do that:
private ObservableCollection<string> _listOne;
private ObservableCollection<string> _listTwo;
private string _selectedListOneItem;
private string _selectedListTwoItem;
public ObservableCollection<string> ListOne
{
get { return _listOne; }
set { _listOne = value; }
}
public ObservableCollection<string> ListTwo
{
get { return _listTwo; }
set { _listTwo = value; }
}
public string SelectedListOneItem
{
get { return _selectedListOneItem; }
set { _selectedListOneItem = value; }
}
public string SelectedListTwoItem
{
get { return _selectedListTwoItem; }
set { _selectedListTwoItem = value; }
}
XAML:
<ComboBox ItemsSource="{Binding ListOne}" SelectedItem="{Binding SelectedListOneItem}"/>
<ComboBox ItemsSource="{Binding ListTwo}" SelectedItem="{Binding SelectedListTwoItem}"/>
You have several options in how you want to load or get your lists. You can either load them in the constructor or for something a bit heavier is load them every time you "get" in the property. I would recommend loading those in the constructor.
What I provided is basically autoprops and can even be further simplified but I wanted to show you that you can also write code in the getter and setter of those properties to further expand on the items. For instance, you may want something on the background to fire off when SelectedListOneItem changes. In this case on the SET of SelectedListOneItem you can set the value but then also run a method/function which may update other properties.
WPF is very dependent on properties to bind between ViewModels and Views. In your response before the edit you are using fields which can't be bound to controls in a view.
EDIT:
If you do plan on updating properties in the ViewModel that would change things on the view you are also going to want to look into INotifyPropertyChanged. By implementing INotifyPropertyChanged the view will be updated/notified when properties are changing. INotifyPropertyChanged comes with it's own event that you must invoke in the setting of a property. Here is also a very helpful method you can call that will fire this event for you much easier.
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
You call this like so:
public string SelectedListOneItem
{
get { return _selectedListOneItem; }
set
{
_selectedListOneItem = value;
OnPropertyChanged();
}
}
That way if anything else in the ViewModel updates SelectedListOneItem that your view will make the appropriate change. In this case it would make the combobox select the new value you set in SelectedListOneItem.

Related

Is DataBinding to a composite object's fields possible?

I have a WPF window with controls I wish to bind to my model. The model implements INotifyPropertyChanged to notify the view when the Properties change value. The Properties are primitives backed by fields, e.g:
private bool m_isRunning;
public bool IsRunning
{
get { return m_isRunning; }
private set
{
m_isRunning= value;
OnPropertyChanged("IsRunning");
}
}
protected virtual void OnPropertyChanged(string propertyName)
{
if (String.IsNullOrEmpty(propertyName))
{
return;
}
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
This works fine for primtiive values. I also have a composite object with various primitive properties and a hash table. Or, I'd like to bind to an ObservableCollection's Count property. I would like to bind my View controls to properties within the composite object, but I do not think this is possible. Something like:
<Run Text="{Binding Path=CompositeObject.SomeInnerProperty, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" />
This doesn't seem possible, but is there some other way? I feel like my only option is to expose properties that map in to the inner property of the composite object, but this seems like a lot of repetiion, e.g.:
public bool SomeInnerProperty
{
get { return m_myComposite.SomeInnerProperty; }
private set
{
m_myComposite.SomeInnerProperty= value;
OnPropertyChanged("SomeInnerProperty");
}
}
There's nothing wrong with binding to something like CompositeObject.SomeInnerProperty, however if CompositeObject does not implement INotifyPropertyChanged, then your UI won't get notified of the change and know that it needs to update when SomeInnerProperty changes.
Also, note that you can only bind to properties (with get and set methods), and not fields. So you can bind to public string SomeValue { get; set; } but you can't bind to public string SomeValue;
In regards dealing with repetitive code, I personally use some Visual Studio macros to write my public properties for me, so perhaps you could look into doing something like that if you don't want to implement INotifyPropertyChanged on your CompositeObject class. It should be noted that Macros were removed from Visual Studio 2012 though, so if you have a newer version you might need to use some other alternative like creating an add-in to run your macros
I had this same problem some time ago. Look at how I solved it:
MVVM INotifyPropertyChanged conflict with base class PropertyChange
Basically I created a Base class that implemented INotifyPropertyChanged and I made all my classes inherit from that base class and data binding worked fine.
You have two options:
If your model classes do not implement INPC, then create wrapper properties in your ViewModel like you suggested, or
Implement INPC in your model and just expose your main object in the ViewModel, you can bind as deep as you want as long as inner properties notify changes.

Updating a dependency property based on changes in the view model

I'm having some problems with data binding in WPF. Here's the scenario: I have made a user control which simulates a Dial Pad (i.e., an array of 12 buttons with the digits from '0' to '9' plus the '#' and 'Clear' keys). The control lives inside a class library and it's been implemented following the MVVM pattern, mainly because I need the components in the class library to be easily unit tested.
The view model for the control is quite simple, it basically updates a public "DialedNumber" string (which is internally connected to the model) every time the user presses a dial pad key button. The binding is working correctly and, by using the debugger, I can confirm that the "DialedNumber" variable inside the viewmodel is getting updated as I press button in the dial pad.
This DialPad control is used by a separate XAML file (Panel.xaml), which laids out several controls that belong to my custom class library.
Now, I'd like to add a TextBlock inside my Panel file in order to display the "DialedNumber" string held inside the DialPad. This is the code snippet in Panel.xaml:
<PanelControls:DialPad x:Name="MyDialPad" DialedNumber="55325"/>
<TextBlock Text="{Binding ElementName=MyDialPad, Path=DialedNumber}" />
The result I'm getting is that the textblock displays the correct number on start (i.e., "55325"), but its content doesn't get updated as I press the dial pad keys (even though the DialPad's viewmodel gets updated as I press new keys, as I've checked with the debugger).
Here's the code behind for the DialPad view:
public partial class DialPad : UserControl
{
public DialPad()
{
InitializeComponent();
DataContext = new DialPadViewModel();
}
public void DialedNumberChanged(object sender, EventArgs e)
{
return;
}
public DialPadViewModel DialPadViewModel
{
get { return DataContext as DialPadViewModel; }
}
public string DialedNumber
{
get
{
var dialPadViewModel = Resources["DialPadVM"] as DialPadViewModel;
return (dialPadViewModel != null) ? dialPadViewModel.DialedNumber : "";
}
set
{
var dialPadViewModel = Resources["DialPadVM"] as DialPadViewModel;
if (dialPadViewModel != null)
{
dialPadViewModel.DialedNumber = value;
}
}
}
}
Here's the DialPad view model:
public class DialPadViewModel : ObservableObject
{
public DialPadViewModel()
{
_dialPadModel = new DialPadModel();
}
#region Fields
private readonly DialPadModel _dialPadModel;
private ICommand _dialPadKeyPressed;
#endregion
#region Public Properties/Command
public DialPadModel DialPadModel
{
get { return _dialPadModel; }
}
public ICommand DialPadKeyPressedCommand
{
get
{
if (_dialPadKeyPressed == null)
{
_dialPadKeyPressed = new RelayCommand(DialPadKeyPressedCmd);
}
return _dialPadKeyPressed;
}
}
public string DialedNumber
{
get { return _dialPadModel.DialedNumber; }
set
{
_dialPadModel.DialedNumber = value;
RaisePropertyChanged("DialedNumber");
}
}
#endregion
#region Private Helpers
private void DialPadKeyPressedCmd(object parameter)
{
string keyPressedString = parameter.ToString();
if (keyPressedString.Length > 0)
{
if (char.IsDigit(keyPressedString[0]))
{
DialedNumber += keyPressedString[0].ToString(CultureInfo.InvariantCulture);
}
else if (keyPressedString == "C" || keyPressedString == "Clr" || keyPressedString == "Clear")
{
DialedNumber = "";
}
}
}
#endregion
}
Let me restate my problem: the textblock in Panel.xaml displays the correct number (55325) on start, but its value never gets updated as I press the DialPadButtons. I've placed a breakpoint inside DialPadKeyPressedCmd and I can confirm that the method gets executed everytime I press a key in the dial pad.
DependencyProperties are meant to point to some other property to get their value. So you can either point it to your DialPadViewModel.DialedNumber, or you can point it to some other string when the UserControl is used (either a binding or a hardcoded value like "551"), but you can't do both.
In your case, when someone binds to the DialedNumber dependency property, they are replacing the current value (the binding to DialPadViewModel.DialedNumber) with a new value.
Depending on how your code looks and what you want to do, there are a few ways around it.
First, you could insist that people who want to use your control also use your ViewModel, and don't make DialedNumber a public dependency property.
So instead of being allowed to create a custom class with a property of SomeOtherDialedNumber and binding
<DialPad DialedNumber="{Binding SomeOtherDialedNumber}">
they are forced to use the DialPadViewModel in their code anytime they want to use the DialPad control. For this to work, you would need to remove the this.DataContext = new DialPadViewModel in your code-behind the UserControl since the user will be providing the DialPadViewModel to your UserControl, and you can use an implicit DataTemplate to tell WPF to always draw DialPadViewModel with your DialPad UserControl.
<DataTemplate DataType="{x:Type DialPadViewModel}">
<local:DialPad />
</DataTemplate>
The other alternative I can think of is to synchronize your DependencyProperty with your ViewModel property with some PropertyChange notifications.
You would need to update DialPadViewModel.DialedNumber anytime the DialedNumber dependency property changes (You may need to use DependencyPropertyDescriptor.AddValueChanged for property change notification), and you would also have to write something to update the source of the DialedNumber dependency property anytime DialPadViewModel.DialedNumber changes.
Personally, if my UserControl has a ViewModel then I use the first option. If not, I get rid of the ViewModel entirely and build the logic for my UserControl in the code-behind, without a ViewModel.
The reason for this is that WPF works with two layers: a UI layer and a data layer. The DataContext is the data layer, and a ViewModel is typically part of the data layer. By setting the data layer (DataContext) explicitly in the UserControl's constructor, you are combining your data layer with your UI layer, which goes against one of the biggest reasons for using MVVM: separation of concerns. A UserControl should really just be a pretty shell only, and you should be able to place it on top of any data layer you want.
If you place your DialPad in your View, you can create a DialPadViewModel-Property (public+global) in your ViewViewModel:
public DialPadViewModel DialPadViewModel = new DialPadViewModel();
Now set the DataContext-Binding of your View to the ViewViewModel and bind the DialPads DataContext also to it, like
<local:DialPad DataContext="{Binding}"/>
Now you can bind to the properties in your DialPadViewModel:
<TextBox Text="{Binding Path=DialPadViewModel.DialedNumber}"/>
Thats how you can Access your DialPadViewModel from your View and your DialPad.
EDIT:
Now try changing your DialedNumber Property in your DialPad.xaml.cs like this:
public string DialedNumber
{
get
{
return DialPadViewModel.DialedNumber;
}
set
{
DialPadViewModel.DialedNumber = value;
}
}
EDIT 2: I found the Problem:
In your DialPad.xaml all your Commands were bound to the DialPadViewModel from the resources, while the TextBloc was bound to the DialPads DataContext, which is another instance of the DialPadViewModel.
So everytime you hit a DialPad-Button you changed the value of the DialedNumber from the resources' DPVM-instance not the DialedNumber from the DataContext's DPVM-instance.
It sounds like you can add a TextBox to your view and bind it's Text property to your view-model's DialedNumber property.
<TextBox Text="{Binding Path=DialedNumber}"></TextBox>
Your view-model property can look something like this:
private string _dialedNumber;
[DefaultValue("551")]
public string DialedNumber
{
get { return _dialedNumber; }
set
{
if (value == _dialedNumber)
return;
_dialedNumber= value;
_yourModel.DialedNumber= _dialedNumber;
this.RaisePropertyChanged("DialedNumber");
}
}
Let me know if I misunderstood your question.

Deselecting ComboBoxItems in MVVM

I am using a standard wpf/mvvm application where i bind combo boxes to collections on a ViewModel.
I need to be able to de-select an item from the dropdown. Meaning, users should be able to select something, and later decide that they want to un-select it (select none) for it. the problem is that there are no empty elements in my bound collection
my initial thought was simply to insert a new item in the collection which would result having an empty item on top of the collection.
this is a hack though, and it affects all code that uses that collection on the view model.
for example if someone was to write
_myCollection.Frist(o => o.Name == "foo")
this will throw a null reference exception.
possible workaround is:
_myCollection.Where(o => o != null).First(o => o.Name == "foo");
this will work, but no way to ensure any future uses of that collection won't cause any breaks.
what's a good pattern / solution for being able to adding an empty item so the user can de-select. (I am also aware of CollectionView structure, but that seems like a overkill for something so simple)
Update
went with #hbarck suggestion and implemented CompositeCollection (quick proof of concept)
public CompositeCollection MyObjects {
get {
var col = new CompositeCollection();
var cc1 = new CollectionContainer();
cc1.Collection = _actualCollection;
var cc2 = new CollectionContainer();
cc2.Collection = new List<MyObject>() { null }; // PROBLEM
col.Add(cc2);
col.Add(cc1);
return col;
}
}
this code work with existing bindings (including SelectedItem) which is great.
One problem with this is, that if the item is completely null, the SelectedItem setter is never called upon selecting it.
if i modify that one line to this:
cc2.Collection = new List<MyObject>() { new MyObject() }; // PROBLEM
the setter is called, but now my selected item is just a basic initialized class instead of null.. i could add some code in the setter to check/reset, but that's not good.
I think the easiest way would be to use a CompositeCollection. Just append your collection to another collection which only contains the empty item (null or a placeholder object, whatever suites your needs), and make the CompositeCollection the ItemsSource for the ComboBox. This is probably what it is intended for.
Update:
This turns out to be more complicated than I first thought, but actually, I came up with this solution:
<Window x:Class="ComboBoxFallbackValue"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:t="clr-namespace:TestWpfDataBinding"
xmlns:s="clr-namespace:System;assembly=mscorlib"
xmlns:w="clr-namespace:System.Windows;assembly=WindowsBase"
Title="ComboBoxFallbackValue" Height="300" Width="300">
<Window.Resources>
<t:TestCollection x:Key="test"/>
<CompositeCollection x:Key="MyItemsSource">
<x:Static Member="t:TestCollection.NullItem"/>
<CollectionContainer Collection="{Binding Source={StaticResource test}}"/>
</CompositeCollection>
<t:TestModel x:Key="model"/>
<t:NullItemConverter x:Key="nullItemConverter"/>
</Window.Resources>
<StackPanel>
<ComboBox x:Name="cbox" ItemsSource="{Binding Source={StaticResource MyItemsSource}}" IsEditable="true" IsReadOnly="True" Text="Select an Option" SelectedItem="{Binding Source={StaticResource model}, Path=TestItem, Converter={StaticResource nullItemConverter}, ConverterParameter={x:Static t:TestCollection.NullItem}}"/>
<TextBlock Text="{Binding Source={StaticResource model}, Path=TestItem, TargetNullValue='Testitem is null'}"/>
</StackPanel>
Basically, the pattern is that you declare a singleton NullInstance of the class you use as items, and use a Converter which converts this instance to null when setting the VM property. The converter can be written universally, like this (it's VB, I hope you don't mind):
Public Class NullItemConverter
Implements IValueConverter
Public Function Convert(value As Object, targetType As System.Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
If value Is Nothing Then
Return parameter
Else
Return value
End If
End Function
Public Function ConvertBack(value As Object, targetType As System.Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
If value Is parameter Then
Return Nothing
Else
Return value
End If
End Function
End Class
Since you can reuse the converter, you can set this all up in XAML; the only thing that remains to be done in code is to provide the singleton NullItem.
Personally, I tend to add an "empty" version of whatever object is in my collection I'm binding to. So, for example, if you're binding to a list of strings, then in your viewmodel, insert an empty string at the beginning of the collection. If your Model has the data collection, then wrap it with another collection in your viewmodel.
MODEL:
public class Foo
{
public List<string> MyList { get; set;}
}
VIEW MODEL:
public class FooVM
{
private readonly Foo _fooModel ;
private readonly ObservableCollection<string> _col;
public ObservableCollection<string> Col // Binds to the combobox as ItemsSource
{
get { return _col; }
}
public string SelectedString { get; set; } // Binds to the view
public FooVM(Foo model)
{
_fooModel = model;
_col= new ObservableCollection<string>(_fooModel.MyList);
_col.Insert(0, string.Empty);
}
}
You could also extend the ComboBox to enable de-selecting. Add one or more hooks (eg, pressing the escape key) that allow the user to set the SelectedItem to null.
using System.Windows.Input;
public class NullableComboBox : ComboBox
{
public NullableComboBox()
: base()
{
this.KeyUp += new KeyEventHandler(NullableComboBox_KeyUp);
var menuItem = new MenuItem();
menuItem.Header = "Remove selection";
menuItem.Command = new DelegateCommand(() => { this.SelectedItem = null; });
this.ContextMenu = new ContextMenu();
this.ContextMenu.Items.Add(menuItem);
}
void NullableComboBox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
{
if (e.Key == Key.Escape || e.Key == Key.Delete)
{
this.SelectedItem = null;
}
}
}
Edit Just noticed Florian GI's comment, the Context Menu might be another good deselect hook to add.
One option would be to create an adapter collection that you expose specifically for consumers that want an initial 'empty' element. You would need to create a wrapper class that implements IList (if you want same performance as with ObservableCollection) and INotifyCollectionChanged. You would need to listen to INotifyCollectionChanged on the wrapped collection, then rebroadcast the events with indices shifted up by one. All of the relevant list methods would also need to shift indices by one.
public sealed class FirstEmptyAdapter<T> : IList<T>, IList, INotifyCollectionChanged
{
public FirstEmptyCollection(ObservableCollection<T> wrapped)
{
}
//Lots of adapter code goes here...
}
Bare minimum if you want to avoid the IList methods is to implement INotifyCollectionChanged and IEnumerable<T>.
One simple approach is to re-template the ComboBox so that when there is an item select a small X appears on the right side of the box. Clicking that clears out the selected item.
This has the advantage of not making your ViewModels any more complicated

Binding guard properties in Caliburn.Micro to properties on a object in the view model

I have a ViewModel class that looks like this.
class MyViewModel : Screen
{
public BindableCollection<MyObject> MyObjects { get; set; }
private MyObject selectedObject;
public MyObject SelectedMyObject
{
get { return selectedObject; }
set
{
selectedObject = value:
//some additional unrelated logic
}
}
public void SaveObject()
{
//some logic
}
public bool CanSaveObject{
get{
//logic to determine if the selectedObject is valid
}
}
That is the relevant code. Now the problem.
MyObject is a class with three properties. In the View I have a ListView that is bound to the MyObjects collection, and three TextBoxes that are bound to the SelectedItem in the ListView.
When I fill in the textboxes, the related object gets changed in the Model, but I want to make sure that the object is in a valid state before you can save it. CanSaveObject has the necessary logic, but the problem is that is never gets called since I don't have any oppurtunity to call NotifyOfPropertyChanged when the textboxes are filled since only the properties of selectedObject are called, and no properties on MyViewModel.
So the question is: Are there any good way to do this without making properties on the ViewModel that encapsulate the properties inside MyObject.
I have got it working if I make properties like these, and then bind to these instead of the SelectedItem directly in the view, but the viewmodel gets cluttered up in the hurry if hacks like this is the only way to do it. I hope it's not :)
public string SelectedObjectPropertyOne{
get{ return selectedObject.PropertyOne; }
set{
selectedObject.PropertyOne = value;
NotifyOfPropertyChange(() => SelectedObjectPropertyOne);
NotifyOfPropertyChange(() => CanSaveObject);
}
}
ActionMessage.EnforceGuardsDuringInvocation is a static boolean field that can be set to enforce a guard check when an action is about to be invoked. This will guard the actual Save action from being invoked, however it will not help with the issue of the UI appearance based on the guard state immediately after an update to the selected model.
Without doing that, the only other modification I could suggest would be to create a VM type for MyObject model and move the validation and save logic there. This would also allow you to simplify your Views...

Silverlight: how to bind List<T> to data grid

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.

Resources