I have a listbox defined in XAML as:
<ListBox x:Name="directoryList"
MinHeight="100"
Grid.Row="0"
ItemsSource="{Binding Path=SelectedDirectories}"/>
The SelectedDirectories is a property on the lists DataContext of type List<DirectoryInfo>
The class which is the datacontext for the listbox implements INotifyPropertyChanged. When the collection changes the items are added successfully to the list however the display does not update until I force the listbox to redraw by resizing it.
Any ideas why?
EDIT: INotifyPropertyChanged implementation
public class FileScannerPresenter : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private FileScanner _FileScanner;
public FileScannerPresenter()
{
this._FileScanner = new FileScanner();
}
public List<DirectoryInfo> SelectedDirectories
{
get
{
return _FileScanner.Directories;
}
}
public void AddDirectory(string path)
{
this._FileScanner.AddDirectory(path);
OnPropertyChanged("SelectedDirectories");
}
public void OnPropertyChanged(string property)
{
if (this.PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
Try
ObservableCollection<DirectoryInfo>
instead - you're triggering a refresh of the entire ListBox for no reason, and you don't need to make your hosting class implement INotifyPropertyChanged - it could easily just be a property of the window. The key is to never set the property to a new instance. So:
class SomeWindow : Window {
public ObservableCollection<DirectoryInfo> SelectedDirectories {get; private set;}
SomeWindow() { SelectedDirectories = new ObservableCollection<DirectoryInfo>(); }
public void AddDirectory(string path) {
SelectedDirectories.Add(new DirectoryInfo(path));
}
}
If you end up using that FileScanner class, you need to implement INotifyCollectionChanged instead - that way, the ListBox knows what to add/remove dynamically.
(See Update below). WPF seems to be working alright. I put your code into a new project. The listbox updates whenever I click the button to invoke AddDirectory. You should not need any more code changes.
The problem seems to be something else.. Are there multiple threads in your UI?
I didnt have the FileScanner type. So I created a dummy as follows.
public class FileScanner
{
string _path;
public FileScanner()
{ _path = #"c:\"; }
public List<DirectoryInfo> Directories
{
get
{
return Directory.GetDirectories(_path).Select(path => new DirectoryInfo(path)).ToList();
}
}
internal void AddDirectory(string path)
{ _path = path; }
}
No changes to your FileScannerPresenter class. Or your listbox XAML. I created a Window with a DockPanel containing your listbox, a textbox and a button.
Update: Paul Betts is right. It works because I return a new list each time from the Bound property. Data binding with lists always messes me up.
With more tinkering, the easy way to do this is:
Make FileScanner#Directories return an ObservableCollection<DirectoryInfo> (which implements INotifyCollectionChanged for you). Change all signatures all the way up to return this type instead of a List<DirectoryInfo>
FileScanner and FileScannerPresenter themselves do not have to implement any INotifyXXX interface.
// in FileScanner class def
public ObservableCollection<DirectoryInfo> Directories
{
get
{ return _DirList; }
}
internal void AddDirectory(string path)
{
_path = path;
//var newItems = Directory.GetDirectories(_path).Select(thePath => new DirectoryInfo(thePath)).ToList();
//_DirList.Concat( newItems ); -- doesn't work for some reason.
foreach (var info in Directory.GetDirectories(_path).Select(thePath => new DirectoryInfo(thePath)).ToList())
{
_DirList.Add(info);
}
}
Related
I am using MVVM in a WPF application with C# and got a problem binding a ComboBox correctly.
This is my ComboBox line in the XAML:
<ComboBox ItemsSource="{Binding Repository.Models}" SelectedValue="{Binding Repository.SelectedModel}" DisplayMemberPath="Name"></ComboBox>
This is the interesting part of my Repository:
class Repository : INotifyPropertyChanged
{
//init MVVM pattern
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private ObservableCollection<Model> _models;
public ObservableCollection<Model> Models
{
get
{
return _models;
}
set
{
_models = value;
NotifyPropertyChanged("Models");
}
}
private Model _selectedModel;
public Model SelectedModel
{
get
{
return _selectedModel;
}
set
{
_selectedModel = value;
NotifyPropertyChanged("SelectedModel");
}
}
This is the interesting part of my Model class:
abstract class Model : INotifyPropertyChanged
{
//init MVVM pattern
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private string _name;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
NotifyPropertyChanged("Name");
}
}
So when I select/change different items of the combobox a DataGrid that is binded to Repository.SelectedModel.Parameters does update just as i want it to.
Because of that I know, that the binding does work!
When I restart the application and debug into my Repository, I see that there is a SelectedModel (deserialised on startup) but the ComboBox stays blank. The DataGrid though does show the right data.
So the binding itself does work, but the binding to the ComboBoxLabel somehow fails.
I tried a lot of things like switching between SelectedItem and SelectedValue, between Binding and Binding Path, between IsSynchronizedWithCurrentItem true and false, but nothing worked so far.
Do you see my mistake?
Thanks in advance!
EDIT
Here is the interesting part of my MainWindowViewModel:
class MainWindowViewModel : INotifyPropertyChanged
{
//init MVVM pattern
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private Repository _repository;
public Repository Repository
{
get
{
return _repository;
}
set
{
_repository = value;
NotifyPropertyChanged("Repository");
}
}
And here is my App.xaml.cs where I init my DataContext:
//init point of app
public partial class App : Application
{
private MainWindowViewModel mainWindowViewModel;
//gets fired as the app starts
protected override void OnStartup(StartupEventArgs e)
{
//create the ViewModel
mainWindowViewModel = new MainWindowViewModel();
//create the mainWindow
var mainWindow = new MainWindow();
mainWindow.DataContext = mainWindowViewModel;
//show the mainWindow
mainWindow.Show();
}
When I restart the application and debug into my Repository, I see that there is a SelectedModel (deserialised on startup) but the ComboBox stays blank. The DataGrid though does show the right data.
Looks like the deserialization is the problem.
You have a selected item which was deserialized. That means that a new Model instance was created which has a Name of whatever, and Properties that are whatever. And you have a list of Model instances in an ObservableCollection<Model> which are displayed in a ComboBox.
And you assure us that at least sometimes, you have ComboBox.SelectedItem bound to SelectedModel, though for some reason the code in your question binds ComboBox.SelectedValue instead. That's not going to work. Here's how ComboBox.SelectedValue would be used:
<ComboBox
ItemsSource="{Binding Repository.Models}"
SelectedValuePath="Name"
SelectedValue="{Binding SelectedModelName}"
/>
...and you would have to have a String SelectedModelName { get; set; } property on your viewmodel. The Name property of the selected Model would be assigned to that by the ComboBox when the selection changed. But you don't have SelectedModelName, and you don't want it, so forget about SelectedValue.
Back to SelectedItem. The ComboBox gets the value of SelectedModel from the binding, and tries to find that exact object in its list of Items. Since that exact object is not in that list, it selects nothing. There is probably an item in Repository.Models that has the same name and has identical Properties, but it is not the same actual instance of the Model class. ComboBox doesn't look for an identical twin of the value in SelectedItem; it looks for the same object.
SelectedModel.Properties works in the DataGrid because the DataGrid doesn't know or care what's in Models. You give it a collection, it's good.
So: If you want to deserialize a SelectedModel and have it mean anything, what you need to do is go ahead and deserialize, but then find the equivalent item in Repository.Models (same Name, same Properties), and assign that actual object instance to SelectedModel.
You may be tempted to overload Model.Equals(). Don't. I've done that to solve the same problem. The resulting behavior is not expected in C# and will bite you, hard, and when you least expect it, because you are invisibly altering behavior that happens in framework code. I've spent days tracking down bugs I created that way, and I'll never do it to myself again.
Try SelectedItem instead of SelectedValue in ComboBox.
I'm having Class call Apps. It has Observable collection called AvailableTypes. I want to bind this AvailableTypes observable collection to the wpf ComboBox. When form is loaded these AppId should loaded into comboBox.. Would you give me a solution to this one?
class Apps: INotifyPropertyChanged{
ServiceReference1.AssetManagerServiceClient client;
ObservableCollection<string> availableType;
public ObservableCollection<string> AvailableTypes
{
get
{
if (availableType == null)
{
availableType = new ObservableCollection<string>();
}
client = new ServiceReference1.AssetManagerServiceClient();
List<string> AssestList = client.GetAppIds().ToList<string>();
foreach (string appid in AssestList)
{
availableType.Add(appid);
}
return availableType;
}
set
{
availableType = value;
NotifyPropertyChanged("AvailableTypes");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
In your xaml code, this is a simple example of how you can bind to your combobox.
<ComboBox ItemsSource={Binding Path=AvailableTypes} />
You will also need to load your viewmodel into the DataContext of your window too.
var window = new MainWindow
{
DataContext = new Apps()
};
window.Show();
If you want open the window on App startup, you can do this instead
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var window = new MainWindow
{
DataContext = new Apps()
};
window.Show();
}
}
Don't overload property getters/setters. Make it simplier.
I recommend to use auto properties and NotifyPropertyWeaver or use PostSharp post build compile-time injected instuctions to support INotifyPropertyChanged interface.
This makes your view model more readable and easy to manage/understand.
In your form 'Loaded' event or 'NavigatedTo' in SL you can start loading your data from anywhere you want and set corresponding properties after loading completed (in callbacks/events handlers, don't forget about using UI dispatcher while updating binded properties)
The problems is simple: when ItemsSource is updated Combobox doesn't "refresh" e.g. new items don't appear to be added to the list of items in the combobox.
I've tried the solution from aceepted answer to this question: WPF - Auto refresh combobox content with no luck.
here's my code,
XAML:
<ComboBox Name="LeadTypeComboBox" ItemsSource="{Binding LeadTypeCollection}" />
ViewModel:
public ObservableCollection<XmlNode> LeadTypeCollection { get; set; }
the way I update this collection is in the separate method, which loads data from updated XML file: this.LeadTypeCollection = GetLeadTypesDataSource();
I've also tried using Add for testing purposes:
this.LeadTypeCollection = GetLeadTypesDataSource();
ItemToAdd = LeadTypeCollection[LeadTypeCollection.Count - 1];
this.LeadTypeCollection.Add(ItemToAdd);
the code updating collection definitely kicks off, I can see new items in this collection when debugging, but I don't see them in the combobox.
Doing this in the xaml code-behind works: LeadTypeComboBox.ItemsSource = MyViewModel.GetLeadTypesDataSource(); but I'd like to achieve this with MVVM, i.e. the code must be in ViewModel which isn't aware of LeadTypeComboBox control.
Firedragons answer would work, but i would prefer to initialize the LeadTypeCollection just once and use clear, add remove to update your collection.
var update = GetLeadTypesDataSource();
this.LeadTypeCollection.Clear();
foreach(var item in update)
{
this.LeadTypeCollection.Add(item);
}
your xaml binding should work if the datacontext is right
<ComboBox Name="LeadTypeComboBox" ItemsSource="{Binding LeadTypeCollection}" />
I think I have seen this before and the solution was to update the collection property to raise the change.
i.e.
public class MyViewModel : INotifyPropertyChanged
{
private ObservableCollection<XmlNode> leadTypeCollection;
public string LeadTypeCollection
{
get { return leadTypeCollection; }
set
{
if (value != leadTypeCollection)
{
leadTypeCollection = value;
NotifyPropertyChanged("LeadTypeCollection");
}
}
public MyViewModel()
{
leadTypeCollection = new ObservableCollection<XmlNode>();
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
PropertyChanged.Raise(this, info);
}
}
I have an extension method for raising the property (as found elsewhere on stackoverflow):
public static void Raise(this PropertyChangedEventHandler handler, object sender, string propertyName)
{
if (null != handler)
{
handler(sender, new PropertyChangedEventArgs(propertyName));
}
}
A simple method is to change ItemsSource with empty list and then change it back to your updated source. A snippet from my project which is working:
RulesTable.ItemsSource = Rules.rulesEmpty;
RulesTable.ItemsSource = Rules.Get();
I have a WPF application using MVVM; when I change the ViewModel in my main window ViewModel class, the new user control is not displayed in the window... the original one remains. The ViewModel looks like this:
public class MainWindowViewModel : ViewModelBase
{
public ViewModelBase Workspace;
public MainWindowViewModel()
{
var w = new CustomerDetailsViewModel();
SetActiveWorkspace(w);
}
void NavigationService_ViewChanged(object sender, ViewChangedEventArgs e)
{
SetActiveWorkspace(e.View);
}
void SetActiveWorkspace(ViewModelBase workspace)
{
Workspace = workspace;
}
}
My XAML looks like this:
< ContentControl Content="{Binding Path=Workspaces}" >
The navigation service ViewChanged event is firing, and the SetActiveWorkspace method is being called with the correct view in the argument. However, after that, the view is not reloaded. What am I missing here?
Your Workspace property is not raising the PropertyChanged event. It should look like this:
private ViewModelBase _workspace;
public ViewModelBase Workspace
{
get { return _workspace; }
set
{
if (value != _workspace)
{
_workspace = value;
// This raises the PropertyChanged event to let the UI know to update
OnPropertyChanged("WorkSpace");
}
}
}
Make sure your ViewModelBase implements INotifyPropertyChanged
I have the following class
public class LanguagingBindingSource : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public string Dummy
{
get { return String.Empty; }
set
{
PropertyChanged(this, new PropertyChangedEventArgs("Dummy"));
}
}
}
that is bound to elements in XAML like this
Text="{Binding Dummy,Source={StaticResource languageSource},Converter={StaticResource languageConverter},ConverterParameter=labelColor}"
The sole purpose of the LanguageBindingSource class and its Dummy method is to allow property notifications to update the bindings when one or more resources change. The actual bound values are provided by the converter, looking up resources by the names passed as parameters. See the comments on this answer for more background.
My problem is that the resources are changed by a process external to the XAML pages containing the bindings and I need a single static method that I can call to trigger property change notification for all instances of the binding. I'm struggling to figure out just how I might do that. All ideas will be most appreciated.
Modify your class as follows:-
public class LanguagingBindingSource : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate {};
public static void FirePropertyChanged(string key)
{
((LanguagingBindingSource)Application.Resources[key]).NotifyPropertyChanged("Dummy");
}
private void NotifyPropertyChanged(string name)
{
PropertyChanged(this, new PropertyChangedEventArgs(name);
}
public string Dummy
{
get { return String.Empty; }
set
{
NotifyPropertyChanged("Dummy"));
}
}
}
Now are any point where you need to fire off this change use:-
LanguagingBindingSource.FirePropertyChanged("languageBindingSource");
Where "languageBindingSource" is the resource key that you are also using in your binding Source property.