ItemsControl MVVM Binding - wpf

I have a form that binds to an ViewModel (MVVM). Inside the form I have an ItemsControl that is bound to an element called projects in my DataContext.
When I do a save using a command pattern I save the item and do a retrieve then I want to rebind the ItemsControl to the Projects collection. This part doesn't seem to be working, all my service calls work as expected but my view is not rebound to the new collection with the added item even though it gets returned from the server.
Any help with this would really be appreciated.
XAML
<ItemsControl Name="ProjectGrid"
Background="Transparent" ItemsSource="{Binding Path=Projects}" Margin="0,0,0,0" VerticalAlignment="Top"
ItemContainerStyle="{StaticResource alternatingWithTriggers}"
AlternationCount="2"
ItemTemplate="{StaticResource ItemTemplate}"/>
ViewModel
public ICommand SaveCommand
{
get
{
if (_cmdSave == null)
{
_cmdSave = new RelayCommand(Save, CanSave);
}
return _cmdSave;
}
}
public void Save()
{
MyService.Save();
PopulateModel();
}
private void PopulateModel()
{
Projects = MyService.GetProjects();
}
public ProjectDto[] Projects
{
get { return _projects; }
set
{
if (_projects == value)
return;
_projects = value;
Notify(PropertyChanged, o => Projects);
}
}

Make sure your ViewModel is implementing INotifyPropertyChanged. Your ui wont know about the change if your view model doesnt inform it when the property changes
use a debug converter to ascertain if your binding is failing. there is an example here of how to do this. This is a technique every wpf developer needs.
im pretty sure its your NotifyPropertyChanged that is failing, the debug converter will tell you for certain

As Aran Mulholland already said, implement INotifyPropertyChanged in your ViewModel.
Also, try to use an ObservableCollection for your collections.
And instead of resetting the collection, try to use
Projects.Clear();
MyService.GetProjects().ToList().ForEach(Projects.Add);
And just as a tip, try to make the GetProjects() method async, so it won't block the UI...

Related

WPF MVVM ListBox/ComboBox ItemsSource won't update UI from ViewModel

i have a container such as a listbox, combobox etc that its ItemsSource property is bound to an observable collection in my view model.
When i'm trying to add/remove items from the collection via some method in my VM it won't reflect in the UI,
The only way the UI would actually refresh is if i assign the collection a new value (i.e another collection with the relevant data) which forces him to re-bind the whole collection.
maybe i'm missing/don't understand something about the collection binding issue, either way if someone has a solution/good explanation/both it would be great.
here is a sample from my View(in this case its a listbox)
<ListBox
Grid.Row="9"
Grid.Column="1"
Grid.ColumnSpan="3"
Width="200"
Height="200"
ItemsSource="{Binding PreSavedRecordingScheduleList,UpdateSourceTrigger=PropertyChanged}"
SelectedItem="{Binding SelectedPreSavedRecordingSchedule,UpdateSourceTrigger=PropertyChanged}"
DisplayMemberPath="Display"/>
and here is my ViewModel:
private ObservableCollection<ScheduledRecordingObject> m_PreSavedRecordingScheduleList;
PreSavedRecordingScheduleList = new ObservableCollection<ScheduledRecordingObject>();
public ObservableCollection<ScheduledRecordingObject> PreSavedRecordingScheduleList
{
get
{
return m_PreSavedRecordingScheduleList;
}
set
{
m_PreSavedRecordingScheduleList = value;
OnPropertyChanged("PreSavedRecordingScheduleList");
}
}
ScheduledRecordingObject also implements INotifyPropertyChanged.
viewmodel
public ObservableCollection<yourType> MyItemsSource {get;set}
initialize once in contructor and use clear, add and remove to alter it
view
<ListBox ItemsSource="{Binding MyItemsSource}"/>
just be sure that the right DataContext is set.
thats how it should look in your code
EDIT:
some hints to your posted code:
//remove the UpdateSourceTrigger=PropertyChanged - makes no sense the Mode is OneWay anyway :)
ItemsSource="{Binding PreSavedRecordingScheduleList}"
//the following line should just called once and at best in ctor
//but the binding will of course work too when you assign a new collection
PreSavedRecordingScheduleList = new ObservableCollection<ScheduledRecordingObject>();
all in all your code looks good, and if the viewmodel is the Datacontext of your Listbox then it should work. let me know what Snoop is showing :)
Remove the OnPropertyChanged("PreSavedRecordingScheduleList"); from the ObservableCollection. Actually you don't need a backing field. Attach the CollectionChanged event on the ObservableCollection, something like this
1- Inside the ViewModel constructor attach the event CollectionChanged
PreSavedRecordingScheduleList = new ObservableCollection<ScheduledRecordingObject>();
PreSavedRecordingScheduleList.CollectionChanged += PreSavedRecordingScheduleList_CollectionChanged;
2- Inject the OnPropertyChanged("PreSavedRecordingScheduleList") in the event handler
void PreSavedRecordingScheduleList_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
OnPropertyChanged("PreSavedRecordingScheduleList");
}

How can I realize SelectionChanged in MVVM ListBox Silverlight

The ListBox control does not implement a Command property. I have to attach some functionality to the SelectionChanged event. Somebody knows how can I do it? Please help me
I prefer using a binding to the SelectedItem and implementing any functionality in the setting of the binding property.
<ListBox ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}" />
...
public class ViewModel
{
public IEnumerable<Item> Items { get; set; }
private Item selectedItem;
public Item SelectedItem
{
get { return selectedItem; }
set
{
if (selectedItem == value)
return;
selectedItem = value;
// Do logic on selection change.
}
}
}
This is the way where You can Reach the Selection changed events in Your MVVM Application
First Of all i tell you that Command Property only work in Button now we have to Explicitly
binding that property in our Selection Changed event like List box or combo box
in Your XMAL file
<ListBox Name="MyListBox" ItemsSource="{Binding ListItems}" Height="150" Width="150" Margin="281,32,-31,118">
<Local:Interaction.Triggers>
<Local:EventTrigger EventName="SelectionChanged">
<Local:InvokeCommandAction Command="{Binding MyCommand}" CommandParameter="{Binding ElementName=MyListBox,Path=SelectedItem}"/>
</Local:EventTrigger>
</Local:Interaction.Triggers>
</ListBox>
for this you have to add dll Syatem.Windows.Interactivity
now u have to add references in your xaml file namespace like
xmlns:Local="clr-namespace:System.Windows.Interactivityassembly=System.Windows.Interactivity"
in your ViewModel Class you have to define your Command in Con structure
public ViewModel123()
{
MyCommand = new RelayCommand<string>(TestMethod);
}
now create the TestMethod method which can handle the selection changed event
private void TestMethod(string parameter)
{
MessageBox.Show(parameter);
}
i hope this may help u.
Basically you have a few options:
Use the property SelectedItem of ListBox to bind to a property in the backend (ie in view model) and perform logic in the setter as described by Cameron MacFarland.
Use a third party library that has a generic event to command behavior like in the link posted by Pedro Lamas.
If you don't want to use third party libraries or writing logic inside property setter is somehow unacceptable you can create your own behavior for ListBox control. It would subscribe to control's SelectionChanged event and execute a command (the command could be a dependency property exposed by the behavior).
Think this post from Laurent Bugnion will help you solve the problem:
http://geekswithblogs.net/lbugnion/archive/2010/05/19/handling-datagrid.selecteditems-in-an-mvvm-friendly-manner.aspx
The post above mentions the DataGrid but I do think it will work with the ListBox too!
Best regards and Happy New Year!! :)
I would suggest using RelayCommand. Either use the MVVM Light Toolkit or just use the RelayCommand and CommandManager classes from Josh Smith's implementations. I personally use just the two classes, so I don't need the entire toolkit.
While this will definitely work, there might be an easier way depending on what you are doing. It might just be easier to bind an object to the SelectedValue of the ListBox and listen for that value to change.

How to know that property was changed from View

My silverlight project uses MVVM.For examlpe, I have textbox, that binded to ViewModel property. Textbox content can change from View or ViewModel. I need know when content changed from View. How can I implement this accordingly MVVM?
If your viewmodel has INotifyPropertyChanged/INotifyPropertyChanging implemented then you can hook into it. That works for me.
if you use bindings, you get the information in your setter.
Here is a little example:
XAML:
<TextBox Text="{Binding MyProperty, Mode=TwoWay}" />
C# of your ViewModel:
private string myProperty = "Test";
public String MyProperty
{
get { return myProperty; }
set
{
Debug.WriteLine("Property set");
myProperty = value;
NotifyPropertyChanged("MyProperty");
}
}
Each time, you change the text and the TextBox looses the focus, the setter get called.
If you want to get the setter called each time you hit a key, have a look here. This is a little bit of a quick and dirty solution for triggering the binding ;) A better way would be to write an Behaviour for this.
Hope this helps!
BR,
TJ

How to rollback selected SelectedValue of the combo box using WPF MVVM

I have something like it will pop to the user for getting confirmation of changes. If he clicks no I am setting the selectedValue in view model to the previous selection. But its not getting displayed correctly in view. Please help.
Very simple solution for .NET 4.5.1+:
<ComboBox SelectedItem="{Binding SelectedItem, Delay=10}" ItemsSource="{Binding Items}" />
It's works for me in all cases.
Just fire NotifyPropertyChanged without value assignment to rollback.
If the user clicks no and you try to revert the value and then call OnPropertyChanged, WPF will swallow the event since it is already responding to that event. One way to get around this is to use the dispatcher and call the event outside of the current event context.
System.Windows.Threading.Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() => { OnPropertyChanged("ComSelectedValue"); }), null);
WPF seems to validate that the bound property has changed before updating the UI. So simply invoking an NotifyPropertyChanged()/OnPropertyChanged() doesn't do the trick.
The problem is that since the property hasn't changed, WPF doesn't think it needs to refresh the combo box.
here is the incredibly hackish way I handle it in my ViewModels;
private int _someProperty = -1;
public int SomeProperty
{
if (_someProperty != -1 && doYesNo() == Yes)
{
_someProperty = value;
}
else if (_someProperty != -1)
{
int oldValue = _someProperty;
_someProperty = -1; // Set to a different/invalid value so WPF sees a change
Dispatcher.BeginInvoke(new Action(() => { SomeProperty = oldValue; }));
}
else
{
_someProperty = value;
}
NotifyPropertyChanged("SomeProperty");
}
Not pretty but it works reliably.
Assumptions:
- You show a dialog box (with a message and OKCancel buttons) when a user selects some value from ComboBox.
- If user presses OK, everything is OK. :)
- If user presses Cancel, you say vmPropSelectedValue=previousValue.
This won't work. Why?
Don't have exact answer, but I believe when you show the dialog the system has just changed the selected value and has just notified the Source (via binding infrastructure) about the changed value . If at this moment (when source has control) you now change the value of ViewModel property from your VM code, which you expect would trigger OnPropertyChanged of INotifyPropertyChanged, which you expect would ask the WPF to update the target with your requested value. However, the WPF has not yet completed the cycle - its still waiting for the Source to return the control back to it. So it simply rejects your request (otherwise it would go in infinite loop).
If this was confusing, try this:
Cycle starts:
1. User changes value on UI. WPF changes target.
2. binding infrastructure requests Source to update itself.
3. Source updates itself (VM property).
4. Source returns control back to binding infra.
Cycle End.
Experts: Can't find some documentation in this regard. Above is my belief how things work. Please rectify if incorrect.
Short Answer:
AFAIK, this can't be done via pure VM code alone. You will have to put some code-behind code.
Here's one way: http://www.amazedsaint.com/2008/06/wpf-combo-box-cancelling-selection.html
In most WPF applications you bind a view model to the user interface with a TwoWay mode and then you're set to go.
However this goes against the typical user experience, where when you edit something and you don't save, you don't see that editing reflected throughout your entire application, even if you don't save your changes to the Database.
The mechanism available in WPF is the UpdateSourceTrigger property of the Binding. With this property you can control when the User Interface updates the ViewModel that it is bound to. This allows you to update only when the user saves what he's editing or something similar.
An example of a XAML Binding with the UpdateSourceTrigger set to Explicit:
"{Binding Path=Privado, UpdateSourceTrigger=Explicit, Mode=TwoWay}"
And when you want to really save to the ViewModel you call:
UpdateSource();
What if you tried to raise the property changed event asynchronously? This is similar the examples from shaun and NebulaSleuth.
public int SomeProperty
{
get { return m_someProperty; }
set
{
if (value == m_someProperty)
return;
if (doYesNo() == No)
{
// Don't update m_someProperty but let the UI know it needs to retrieve the value again asynchronously.
Application.Current.Dispatcher.BeginInvoke((Action) (() => NotifyOfPropertyChange("SomeProperty")));
}
else
{
m_someProperty = value;
NotifyOfPropertyChange("SomeProperty");
}
}
}
Here is the general flow that I use:
I just let the change pass through the ViewModel and keep track of whatever's passed in before.
(If your business logic requires the selected item to not be in an invalid state, I suggest moving that to the Model side). This approach is also friendly to ListBoxes that are rendered using Radio Buttons as making the SelectedItem setter exit as soon as possible will not prevent radio buttons from being highlighted when a message box pops out.
I immediately call the OnPropertyChanged event regardless of the value passed in.
I put any undo logic in a handler and call that using SynchronizationContext.Post()
(BTW: SynchronizationContext.Post also works for Windows Store Apps. So if you have shared ViewModel code, this approach would still work).
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public List<string> Items { get; set; }
private string _selectedItem;
private string _previouslySelectedItem;
public string SelectedItem
{
get
{
return _selectedItem;
}
set
{
_previouslySelectedItem = _selectedItem;
_selectedItem = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("SelectedItem"));
}
SynchronizationContext.Current.Post(selectionChanged, null);
}
}
private void selectionChanged(object state)
{
if (SelectedItem != Items[0])
{
MessageBox.Show("Cannot select that");
SelectedItem = Items[0];
}
}
public ViewModel()
{
Items = new List<string>();
for (int i = 0; i < 10; ++i)
{
Items.Add(string.Format("Item {0}", i));
}
}
}
I realize this is an old post but it seems no one has done this the right way. I used System.Interactivity.Triggers and Prism to process the SelectionChanged event and manually trigger the SelectedItem. This will prevent undesired Selected Item Changes in both the UI and the View-Model.
My view:
<Window x:Class="Lind.WPFTextBlockTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:Lind.WPFTextBlockTest"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:prism="clr-namespace:Microsoft.Practices.Prism.Interactivity;assembly=Microsoft.Practices.Prism.Interactivity"
Title="MainWindow" Height="649" Width="397">
<Window.DataContext>
<vm:MainWindowViewModel/>
</Window.DataContext>
<StackPanel>
<ComboBox ItemsSource="{Binding Data}" SelectedItem="{Binding SelectedData, Mode=OneWay}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<prism:InvokeCommandAction Command="{Binding TryChangeSelectedData}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</ComboBox>
</StackPanel>
My View-Model (BindeableBase and DelegateCommand from Prism 5):
public class MainWindowViewModel : BindableBase
{
public ObservableCollection<string> Data { get; private set; }
private string selectedData;
public string SelectedData
{
get { return selectedData; }
set
{
SetProperty(ref selectedData, value);
}
}
public DelegateCommand<SelectionChangedEventArgs> TryChangeSelectedData { get; private set; }
public MainWindowViewModel()
{
Data = new ObservableCollection<string>() { "Foo", "Bar", "Dick", "Head" };
SelectedData = Data.First();
TryChangeSelectedData = new DelegateCommand<SelectionChangedEventArgs>(args =>
{
var newValue = args.AddedItems.Cast<string>().FirstOrDefault();
if (newValue == "Dick")
this.OnPropertyChanged(() => this.SelectedData);
else
SelectedData = newValue;
});
}
}

WPF DataGrid: How do I databind the properties of the SelectedItem to trigger INotifyPropertyChangedEvents?

I'm trying to do this as MVVM as possible:
My Model (InterestTypeEntity) implements INotifyPropertyChanged.
My ViewModel (InterestTypeAllViewModel) has an ObservableCollection that binds to a DataGrid. When changes are made to it, it sends those changes (add/remove) to the Database.
the problem is, I want to also be able to update the database when the properties of the objects within the collection change. I'm not sure how to do that? Here's my code so far...
XAML:
<DataGrid Name="TestGrid" Grid.Row="3" Grid.ColumnSpan="2" AutoGenerateColumns="False"
ItemsSource="{Binding IntTypes}" SelectedItem="{Binding CurrentIntType}">
<DataGrid.Columns>
<DataGridTextColumn Header="Interest ID" Binding="{Binding IntType}" />
<DataGridTextColumn Header="Interested Parties Description" Binding="{Binding Description}" MaxWidth="500" />
</DataGrid.Columns>
</DataGrid>
ViewModel Code:
public ObservableCollection<InterestTypeEntity> IntTypes
{
get { return DataRepository.InterestTypeEntities; }
}
public InterestTypeEntity CurrentIntType { get; set; }
public Int16 IntType
{
get { return CurrentIntType.IntType; }
set
{
if (value != CurrentIntType.IntType)
{
CurrentIntType.IntType = value;
OnPropertyChanged("IntType");
}
}
}
public String Description
{
get { return CurrentIntType.Description; }
set
{
if (value != CurrentIntType.Description)
{
CurrentIntType.Description = value;
OnPropertyChanged("Description");
}
}
}
Don't create a collection of model objects, and don't implement IntType and Description properties on your (current) view model. And unless you have some other reason to do so, don't implement property-change notification in your model.
Instead, make IntTypes a collection of InterestTypeEntityViewModel objects.
This class wraps InterestTypeEntity. It exposes IntType and Description properties that a) wrap the underlying InterestTypeEntity properties and b) performs property change notification. If you make its constructor take an InterestTypeEntity argument, it's easy to populate in your view model:
IntTypes = new ObservableCollection<InterestTypeEntityViewModel>(
DataRepository.InterestTypeEntities.Select(x => new InterestTypeEntityViewModel(x));
Bind the ItemsSource to this collection. (Also, make CurrentIntType a property of type InterestTypeEntityViewModel and raise PropertyChanged when it changes.)
Edit:
If the owning view model needs to be notified when properties change on the items in its collection, it's pretty simple to make it handle the PropertyChanged events they're raising. In your constructor, add:
foreach (InterestTypeEntityViewModel vm in IntTypes)
{
vm.PropertyChanged += InterestTypeEntityViewModel_PropertyChanged;
}
and this method:
private void InterestTypeEntityViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
InterestTypeEntityViewModel vm = (InterestTypeEntityViewModel) sender;
// check e.PropertyName and do whatever you need to do here.
}
Don't forget to unregister the event handler if you remove an object from your collection; otherwise, the child view model objects won't get disposed until the parent one does.
Note, by the way, that by implementing the view models this way, you can exercise a lot of control over your updates to the underlying entity model. For instance, you can implement a command in your parent view model that does all of the updates in a single operation, and another one that lets the user discard all of the changes they've made in the UI without performing an update. And all of this logic is very nicely decoupled from the actual presentation layer.
Please see my answer here. It will give you an observable collection that tells you when the collection changes, or when an item within the collection changes.
General strategy:
Add TwoWay to your binding:
SelectedItem="{Binding CurrentIntType,Mode=TwoWay}"
And then subscribe to the changed event of the observable collection in your ViewModel. When the collection changes, send it to your model/DAL and persist it.

Resources