Wpf Combo Selection - wpf

I have a problem with WPF Combo box.
I bind a List< Pair < String, String> > (Destinations) on my Combo like that :
My pair class is defined like that :
/// <summary>
/// This class represents a pair.
/// </summary>
public class Pair<T, U>
{
#region Properties
/// <summary>
/// Gets or sets the first value.
/// </summary>
public T First
{
get;
set;
}
/// <summary>
/// Gets or sets the second value.
/// </summary>
public U Second
{
get;
set;
}
#endregion
#region Methods
/// <summary>
/// Default constructor
/// </summary>
public Pair()
{
}
/// <summary>
/// Constructor by initialization.
/// </summary>
/// <param name="pFirst">The first value.</param>
/// <param name="pSecond">The second value.</param>
public Pair(T pFirst, U pSecond)
{
this.First = pFirst;
this.Second = pSecond;
}
#endregion
};
I tried to display only the Second property of my pair as Display of my combo. I tried :
DisplayMemberPath={Binding Destinations.Second} but it doesn't work.
Thanks for your answers.

DisplayMemberPath="Second"
That should work as each item will be a Pair.

Related

How to handle ItemChanged Event for Tree View WPF MVVM

Most of the time we face problem in handling the ItemChange or SelectionChanged for tree, After a lot of struggle i found a working solution for myself. Below is the answer
With Below attached property When ever tree Item is selected or selection changed it directly raises the command on that object
public class ControlBehaviour
{
private static IDictionary<object, ICommand> dataContextCommandMap = new Dictionary<object, ICommand>();
private static IDictionary<FrameworkElement, object> elementDataConextMap = new Dictionary<FrameworkElement, object>();
/// <summary>
///
/// </summary>
public static readonly DependencyProperty ControlEventProperty =
DependencyProperty.RegisterAttached("ControlEvent", typeof(RoutedEvent), typeof(ControlBehaviour),
new PropertyMetadata(OnTreeviewSelectionChanged));
/// <summary>
///
/// </summary>
/// <param name="target"></param>
/// <param name="value"></param>
public static void SetControlEvent(DependencyObject target, object value)
{
target.SetValue(ControlEventProperty, value);
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <returns></returns>
public static RoutedEvent GetControlEvent(DependencyObject sender)
{
return sender.GetValue(ControlEventProperty) as RoutedEvent;
}
/// <summary>
/// Command to be executed
/// </summary>
public static readonly DependencyProperty CommandProperty =
DependencyProperty.RegisterAttached("Command", typeof(ICommand),
typeof(ControlBehaviour), new PropertyMetadata(CommandChanged));
/// <summary>
/// Set ICommand to the dependency object
/// </summary>
/// <param name="target">dependency object</param>
/// <param name="value">I command</param>
public static void SetCommand(DependencyObject target, object value)
{
target.SetValue(CommandProperty, value);
}
/// <summary>
/// Get ICommand to the dependency object
/// </summary>
/// <param name="sender">dependency object</param>
/// <returns>ICommand of the dependency object</returns>
public static ICommand GetCommand(DependencyObject sender)
{
return sender.GetValue(CommandProperty) as ICommand;
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
static void OnTreeviewSelectionChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
if (sender != null)
{
TreeView element = sender as TreeView;
if (element != null)
{
if (e.NewValue != null)
{
element.SelectedItemChanged += Handler;
}
if (e.OldValue != null)
{
element.SelectedItemChanged -= Handler;
}
}
}
}
/// <summary>
/// ICommand Changed
/// </summary>
/// <param name="sender">dependency object</param>
/// <param name="e">dependency args</param>
private static void CommandChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
if (sender != null)
{
FrameworkElement cntrl = sender as FrameworkElement;
if (cntrl != null && cntrl.DataContext != null)
{
if (e.NewValue != null)
{
ICommand cmd = e.NewValue as ICommand;
if (cmd != null)
{
elementDataConextMap[cntrl] = cntrl.DataContext;
dataContextCommandMap[cntrl.DataContext] = cmd;
}
}
cntrl.Unloaded += FrameworkElementUnloaded;
}
}
}
/// <summary>
/// Framework element unload, Clears the removes the ICommand
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void FrameworkElementUnloaded(object sender, RoutedEventArgs e)
{
FrameworkElement element = sender as FrameworkElement;
if (element != null && elementDataConextMap.ContainsKey(element))
{
dataContextCommandMap.Remove(elementDataConextMap[element]);
elementDataConextMap.Remove(element);
}
}
/// <summary>
/// Routed Event Handler
/// </summary>
/// <param name="sender">sender</param>
/// <param name="e">EventArgs</param>
static void Handler(object sender, EventArgs e)
{
TreeView treeView = sender as TreeView;
if (treeView != null && treeView.SelectedItem != null && dataContextCommandMap.ContainsKey(treeView.SelectedItem)
&& dataContextCommandMap[treeView.SelectedItem].CanExecute(treeView.SelectedItem))
{
dataContextCommandMap[treeView.SelectedItem].Execute(treeView.SelectedItem);
}
}
}
Below is the XMAL which uses the above Attached property
<TreeView Grid.Row="1" Background="Transparent" ItemsSource="{Binding Directories}" Margin="0,10,0,0" Name="FolderListTreeView"
Height="Auto" HorizontalAlignment="Stretch" Width="300" local:ControlBehaviour.ControlEvent="TreeView.SelectedItemChanged" >
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type local:FileSystem}" ItemsSource="{Binding SubDirectories}">
<Label Content="{Binding Path= Name}" Name="NodeLabel" local:ControlBehaviour.Command="{Binding OnSelect}"/>
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
Below is FileSystem class which is bound in Xaml
/// <summary>
/// Implementation of file system class
/// </summary>
public class FileSystem :BindableBase, IFileSystem, IEnumerable //BindableBase is base class which implemets INotifyPropertyChanged
{
#region Private members
private ObservableCollection<IFileSystem> subDirectoriesField;
private ObservableCollection<IFileSystem> filesField;
#endregion
#region Public properties
/// <summary>
/// Gets and sets all the Files in the current folder
/// </summary>
public ObservableCollection<IFileSystem> SubDirectories
{
get
{
return subDirectoriesField;
}
set
{
if (subDirectoriesField != value)
{
subDirectoriesField = value;
NotifyPropertyChanged("SubDirectories");
}
}
}
/// <summary>
/// Gets and sets all the files in the current folder
/// </summary>
public ObservableCollection<IFileSystem> Files
{
get
{
return filesField;
}
set
{
if (filesField != value)
{
filesField = value;
RaisePropertyChanged("Files");
}
}
}
/// <summary>
/// Gets or sets the type of the file
/// </summary>
public FileSystemType FileType
{
get;
set;
}
/// <summary>
/// Gets or sets the size of the file
/// </summary>
public long Size
{
get;
set;
}
/// <summary>
/// Gets or sets name of the file system
/// </summary>
public string Name
{
get;
set;
}
/// <summary>
/// Gets or sets full path of the file system
/// </summary>
public string FullPath
{
get;
set;
}
/// <summary>
/// object of parent, null if the current node is root
/// </summary>
public FileSystem Parent
{
get;
set;
}
/// <summary>
/// Returns ICommand
/// </summary>
public ICommand OnSelect
{
get
{
return new Command_R(Execute);//Command_R is implemention of your ICommand
}
}
#endregion
#region Constructor
/// <summary>
/// Constructor
/// </summary>
/// <param name="path">path of the folder</param>
/// <param name="parent">object of the parent</param>
public FileSystem(string fullPath, FileSystem parent, FileSystemType
type = FileSystemType.Directory)
{
Name = fullPath != null ? GetNameFileName(fullPath) : fullPath;
FullPath = fullPath;
Parent = parent;
FileType = type;
FilesAndSubDirectoriesDetails(fullPath);
}
#endregion
#region Public methods
/// <summary>
/// Updates the file size if there is a change
/// </summary>
/// <param name="deleteFilzeSize"></param>
public void UpdateFileSize(long deleteFilzeSize)
{
UpdatePredecessor(this, deleteFilzeSize);
}
/// <summary>
/// Gets the enumeration list
/// </summary>
/// <returns>returns the enumeration list</returns>
public IEnumerator GetEnumerator()
{
return SubDirectories.GetEnumerator();
}
#endregion
#region Private methods
/// <summary>
/// Finds the details of the files and sub directories
/// </summary>
/// <param name="fullPath"></param>
private void FilesAndSubDirectoriesDetails(string fullPath)
{
if (FileType.Equals(FileSystemType.Directory))
{
AddFilesAndSubDirectories(fullPath);
CalculateDirectorySize();
}
else
{
//Write code to calcuate the File Size
//Size = FileInfo.GetSize(fullPath);
}
}
/// <summary>
/// Finds and adds the files and sub directories
/// </summary>
/// <param name="fullPath"></param>
private void AddFilesAndSubDirectories(string fullPath)
{
string[] subDirectories = Directory.GetDirectories(fullPath);
SubDirectories = new ObservableCollection<IFileSystem>();
foreach (string directory in subDirectories)
{
SubDirectories.Add(new FileSystem(directory, this));
}
Files = new ObservableCollection<IFileSystem>();
string[] files = File.GetFiles(fullPath);
foreach (string fileName in files)
{
Files.Add(new FileSystem(fileName, this, FileSystemType.File));
}
}
/// <summary>
/// Calculates the current directory size
/// </summary>
private void CalculateDirectorySize()
{
foreach (FileSystem directory in SubDirectories)
{
Size += directory.Size;
}
foreach (FileSystem file in Files)
{
Size += file.Size;
}
}
/// <summary>
/// Updates the file size of the predecessors
/// </summary>
/// <param name="currentNode">current node</param>
/// <param name="deleteFilzeSize">file to be updated</param>
private void UpdatePredecessor(FileSystem currentNode, long deletedFilzeSize)
{
if (currentNode != null)
{
currentNode.Size -= deletedFilzeSize;
UpdatePredecessor(currentNode.Parent, deletedFilzeSize);
}
}
/// <summary>
/// Executes ICommand
/// </summary>
/// <param name="parameter">parameter</param>
private void Execute(object parameter)
{
//Do your Job
MessageBox.Show(FullPath);
}
#endregion
}
And the interface for the class
/// <summary>
/// Type of the file
/// </summary>
public enum FileSystemType
{
/// <summary>
/// File
/// </summary>
File,
/// <summary>
/// Directory
/// </summary>
Directory
}
/// <summary>
/// Interface for File system
/// </summary>
public interface IFileSystem
{
/// <summary>
/// Gets or sets file type
/// </summary>
FileSystemType FileType
{
get;
set;
}
/// <summary>
/// Gets or sets the file size
/// </summary>
long Size
{
get;
set;
}
/// <summary>
/// Gets or sets name of the file system
/// </summary>
string Name
{
get;
set;
}
/// <summary>
/// Gets or sets full path of the file system
/// </summary>
string FullPath
{
get;
set;
}
}

ICustomTypeDescriptor wth XamDataGrid

I have extended the XamDataGrid to support DynamicColumn generation using a DependencyProperty called ColumnSource. Thus the gird now will generate columns dynamically based on a dependency property called "ColumnSource". this idea was inspired from the DevExpress WPF Grid I had used before.
Having said that, I need to mention that I am using Field (not UnBoundField) inside the extended control to generate the columns and binding them to the ViewModel objects. It has worked fine for requirement I had till now.
Now I have a situation where I have a ViewModel that needs to have dynamic properties. Obviously I have ICustomTypeDescriptor in mind.I just am curious is it possible to view data in the XamDataGrid with the following limitations:
.Net 4.0
ICustomTypeDescriptor
Use of field and not UnboundField class for column generations.
Data shown should be two way bindable,
that is change in cell data should change appropriate ViewModel
property.
I am pasting the Extended control's code here. It is very long so I will try to curtail the code responsible for other functionalities.
public class AdvancedXamDataGrid : XamDataGrid
{
#region Static Constructor
static AdvancedXamDataGrid()
{
//Dependency properties overrides if any to be done here.
DataSourceProperty.OverrideMetadata(typeof(AdvancedXamDataGrid), new FrameworkPropertyMetadata(null, DataSourcePropetyChanged));
}
#endregion
#region Dependency Properties
/// <summary>
/// Dependency proeprty for Columns List shown in the Grid Header
/// </summary>
public static readonly DependencyProperty ColumnsSourceProperty = DependencyProperty.Register("ColumnsSource", typeof(IEnumerable),
typeof(AdvancedXamDataGrid), new FrameworkPropertyMetadata(null, OnColumnsSourceChanged));
/// <summary>
/// Gets or sets the <see cref="ColumnsSource"/>.
/// This is a Dependency Property.
/// </summary>
public IEnumerable ColumnsSource
{
get { return GetValue(ColumnsSourceProperty) as IEnumerable; }
set { SetValue(ColumnsSourceProperty, value); }
}
#endregion
#region Dependency Property Property Changed Handlers (static).
/// <summary>
/// The handler is fired when the <see cref="ColumnsSource"/> is changed.
/// </summary>
/// <param name="sender">The dependency object that raises the event.</param>
/// <param name="e">The event argument</param>
private static void OnColumnsSourceChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var control = sender as AdvancedXamDataGrid;
if (null != control)
{
if (null != control._fieldAdornerSettings)
control.DetachAdorner();
control._fieldAdornerSettings = new FieldAdornerSettings();
control._fieldAdornerList = new List<FieldAdorner>();
var oldValue = e.OldValue as IEnumerable;
var newValue = e.NewValue as IEnumerable;
if (BindingOperations.IsDataBound(sender, ColumnsSourceProperty))
control.ColumnsSourceChanged(oldValue, newValue);
}
}
/// <summary>
/// This handler is fired when the data source property changes.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void DataSourcePropetyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var control = sender as AdvancedXamDataGrid;
if (null != control)
{
var dataSource = e.NewValue as IEnumerable;
control.DataSource = dataSource;
}
}
#endregion
#region Instance Properties and Event Handlers
/// <summary>
/// Handles when the <see cref="ColumnsSource"/> is changed.
/// </summary>
/// <param name="oldValue"></param>
/// <param name="newValue"></param>
private void ColumnsSourceChanged(IEnumerable oldValue, IEnumerable newValue)
{
if (null != oldValue)
//I could never figure out why I need this check. But this check is requred for consistent laytout for first time load.Funny I know!
FieldLayouts.Clear(); //Clear the existing columns.
var oldColSource = oldValue as INotifyCollectionChanged;
if (null != oldColSource)
{
oldColSource.CollectionChanged -= oldColSource_CollectionChanged;
//Remove the columns first.
foreach (IGridColumn column in oldValue)
{
RemoveField(column);
}
}
var newColSource = newValue as INotifyCollectionChanged;
if (null != newColSource)
{
newColSource.CollectionChanged += oldColSource_CollectionChanged;
}
if (null != newValue)
{
var fieldLayout = new FieldLayout {IsDefault = true, Key = Convert.ToString(Guid.NewGuid())};
FieldLayouts.Add(fieldLayout);
foreach (IGridColumn col in newValue)
{
AddField(col);
}
DefaultFieldLayout = fieldLayout;
}
}
/// <summary>
/// Fires when the ColumnsSource Collection changes.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void oldColSource_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
//Remove old Items.
foreach (IGridColumn col in e.OldItems)
{
RemoveField(col);
}
//Add new items.
foreach (IGridColumn col in e.NewItems)
{
AddField(col);
}
}
/// <summary>
/// Adds a Field to the wrapped grids FiledCollection.
/// </summary>
/// <param name="column"></param>
private void AddField(IGridColumn column)
{
if (FieldLayouts.Count > 0)
{
var fieldLayout = FieldLayouts[0];
var field = new Field {Name = column.Name, Label = column.DisplayName.ToUpper(), ToolTip = column.ToolTip};
switch (column.ColumnType)
{
// case GridColumnType.Text:
// field.DataType = typeof(string);
// break;
case GridColumnType.Boolean:
var style = new Style(typeof (XamCheckEditor));
style.Setters.Add(new Setter(XamCheckEditor.IsCheckedProperty,
new Binding()
{
Path = new PropertyPath(string.Concat("DataItem.", column.Name)),
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
Mode = BindingMode.TwoWay
}));
field.Settings.EditorType = typeof (XamCheckEditor);
field.Settings.EditorStyle = style;
break;
}
if (column.ColumnType == GridColumnType.Combo)
{
var style = new Style(typeof (XamComboEditor));
style.Setters.Add(new Setter(XamComboEditor.ItemsSourceProperty,
new Binding() {Path = new PropertyPath(column.ItemsSource)}));
style.Setters.Add(new Setter(XamComboEditor.SelectedItemProperty,
new Binding(column.SelectedItemPropertyName) {Mode = BindingMode.TwoWay}));
style.Setters.Add(new Setter(XamComboEditor.DisplayMemberPathProperty, column.DisplayMemberPath));
style.Setters.Add(new Setter(XamComboEditor.ValuePathProperty, column.ValueMemberPath));
field.Settings.EditorType = typeof (XamComboEditor);
field.Settings.EditorStyle = style;
}
if (column.IsReadOnly)
field.Settings.AllowEdit = false;
if (!column.IsVisible)
field.Visibility = Visibility.Collapsed;
fieldLayout.Fields.Add(field);
if (!string.IsNullOrEmpty(column.TemplateKey))
_fieldAdornerList.Add(new FieldAdorner()
{
Name = column.Name,
BindToParentSource = column.BindToParent,
TemplateKey = column.TemplateKey
});
//Register to the property changed notofication.
var propertyNotifier = column as INotifyPropertyChanged;
propertyNotifier.PropertyChanged += propertyNotifier_PropertyChanged;
}
}
/// <summary>
/// Removes a field
/// </summary>
/// <param name="column"></param>
private void RemoveField(IGridColumn column)
{
if (FieldLayouts.Count > 0)
{
var fieldLayout = FieldLayouts[0];
var field = fieldLayout.Fields.FirstOrDefault(f => f.Name.Equals(column.Name));
if (null != field)
fieldLayout.Fields.Remove(field);
var propertyNotifier = column as INotifyPropertyChanged;
propertyNotifier.PropertyChanged -= propertyNotifier_PropertyChanged;
}
}
/// <summary>
/// Event handler for handling property notification.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void propertyNotifier_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
var column = sender as IGridColumn;
if (null != column)
{
var fieldLayout = FieldLayouts[0];
var field = fieldLayout.Fields.FirstOrDefault(f => f.Name.Equals(column.Name));
if (e.PropertyName.Equals("IsVisible"))
{
if (field != null)
field.Visibility = column.IsVisible ? Visibility.Visible : Visibility.Collapsed;
}
if (e.PropertyName.Equals("IsReadOnly"))
{
if (field != null)
field.Settings.AllowEdit = !column.IsReadOnly;
}
}
}
#endregion
}
Here is the IGridColumn contract:
/// <summary>
/// A contract that need to be implemented by an item that needs to participate in ColumnSource binding.
/// </summary>
public interface IGridColumn : INotifyPropertyChanged
{
/// <summary>
/// Gets or sets the PropertyName to which the Column would bind.
/// </summary>
string Name { get; set; }
/// <summary>
/// Gets or sets the Display Text that will be visible in the column header.
/// </summary>
string DisplayName { get; set; }
/// <summary>
/// Gets the type of the property that gets bound to this column.
/// </summary>
GridColumnType ColumnType { get; }
/// <summary>
/// Gets or sets if the column is read-only.
/// </summary>
bool IsReadOnly { get; set; }
/// <summary>
/// Gets or sets if the column is visible.
/// </summary>
bool IsVisible { get; set; }
#region For Combo Columns
/// <summary>
/// Gets or sets the Items source of the combo editor.
/// </summary>
string ItemsSource { get; set; }
/// <summary>
/// Gets or sets the SelectedItem propertyName.
/// </summary>
string SelectedItemPropertyName { get; set; }
/// <summary>
/// Gets or sets the name of the property that be the display item of the combo.
/// </summary>
string DisplayMemberPath { get; set; }
/// <summary>
/// Gets or sets the name of the property that be the value item of the combo.
/// </summary>
string ValueMemberPath { get; set; }
/// <summary>
/// Gets or sets the tool tip on the column.
/// </summary>
string ToolTip { get; set; }
/// <summary>
/// Gets or sets the Template Key for the adorner.
/// </summary>
string TemplateKey { get; set; }
/// <summary>
/// Gets or sets if the smart tag, would be bound to the view model of the grid.
/// <remarks>
/// Note: By default it would be bound to an item of the grid.
/// </remarks>
/// </summary>
bool BindToParent { get; set; }
/// <summary>
/// Gets or sets the caption for the smart tag.
/// </summary>
string SmartTagCaption { get; set; }
#endregion
}
/// <summary>
/// An enumeration offering various types of Grid Column types.
/// </summary>
public enum GridColumnType
{
Text=0,
Boolean,
Integer,
Double,
Decimal,
Combo
} ;
I had the plan to populating the ColumnSource for the Grid and bind them to ICustomTypeDescriptor instances of ViewModels whose Dynamic property names would match with the IGridColumn Names.

While Launching View error : "Cannot perform this operation while dispatcher processing is suspended"

When I try to launch the View from the constructor of anothers Views ViewModel i get the Error :
Cannot perform this operation while dispatcher processing is suspended
ViewModel of My View from Where i am launching (a UserControl)
public class ExecutionViewModel : BaseViewModel
{
#region Member Variables
/// <summary>
/// Logger
/// </summary>
private static readonly ILog log =
LogManager.GetLogger(typeof(ConfigurationViewModel));
#endregion
#region Properties
/// <summary>
/// Get/Set ExitCommand
/// </summary>
public ICommand ExitCommand { get; set; }
/// <summary>
/// Command To Launch Report a Problem
/// </summary>
public ICommand ReportAProblemView { get; set; }
/// <summary>
/// Command To Launch About
/// </summary>
public ICommand AboutView { get; set; }
/// <summary>
/// LaunchNavigationkeyViewCommamd
/// </summary>
public ICommand LaunchSelectionScreenCommamd { get; set; }
#endregion
# region Constructor
/// <summary>
/// Default Constructor
/// </summary>
public ExecutionViewModel()
{
ExitCommand = new RelayCommand(ExitFromApplication);
ReportAProblemView = new RelayCommand(LaunchReportAProblemView,
CanLaunchReportAProblemView);
AboutView = new RelayCommand(LaunchAboutView, CanLaunchAboutView);
LaunchNavigationkeyViewCommamd = new RelayCommand(LaunchNavigationkeyView);
LaunchSelectionScreenCommamd =
new RelayCommand(LaunchSelectionScreenView);
LaunchMenuConfigViewCommamd = new RelayCommand(LaunchMenuConfigView);
Messenger.UnRegister(this);
Messenger.Register(this);
UpdateStatusBar();
//Here i am Trying to perfrom Somecheck and Launch View if Needed
InitiateStartUpValidations();
}
Private void InitiateStartUpValidations()
{
if (Utility.IsStringNullOrEmpty(DOEConfigFileName))
{
PasswordViewModel passwordViewModel = new PasswordViewModel(FileDialogModes.Open) { ShowPasswordBox = false };
// Launching View using Messenger
// This Gives an error
Messenger.NotifyColleagues(MessengerMessages.LAUNCH_FILE_SELECT_VIEW, passwordViewModel);
}
}
/// <summary>
/// LaunchMenuConfigView
/// </summary>
/// <param name="obj"></param>
private void LaunchMenuConfigView(object obj)
{
log.Debug("LaunchMenuConfigView" + BaseModel.FUNCTION_ENTERED_LOG);
MenuConfigViewModel menuConfigViewModel =
new MenuConfigViewModel();
Messenger.NotifyColleagues(MessengerMessages.LAUNCH_VIEW_MENU_CONFIG, menuConfigViewModel);
log.Debug("LaunchMenuConfigView" + BaseModel.FUNCTION_EXIT_LOG);
}
/// <summary>
/// LaunchSelectionScreenView
/// </summary>
/// <param name="obj"></param>
private void LaunchSelectionScreenView(object obj)
{
log.Debug("LaunchSelectionScreenView" + BaseModel.FUNCTION_ENTERED_LOG);
SelectionScreenViewModel selectionScreenViewModel =
new SelectionScreenViewModel();
Messenger.NotifyColleagues(MessengerMessages.LAUNCH_SELECTIONSCREEN_VIEW, selectionScreenViewModel);
log.Debug("LaunchSelectionScreenView" + BaseModel.FUNCTION_EXIT_LOG);
}
# endregion
# region Private Methods
/// <summary>
/// CanLaunchSelectPageDefinitionView
/// </summary>
/// <param name="obj"></param>
private void CanLaunchSelectPageDefinitionView(object obj)
{
}
/// <summary>
/// LaunchNavigationkeyView
/// </summary>
private void LaunchNavigationkeyView(object obj)
{
log.Debug("LaunchNavigationkeyView" + BaseModel.FUNCTION_ENTERED_LOG);
UtilityViewModel utilityViewModel = new UtilityViewModel();
Messenger.NotifyColleagues(MessengerMessages.LAUNCH_VIEW_NAVIGATIONKEY, utilityViewModel);
log.Debug("LaunchNavigationkeyView" + BaseModel.FUNCTION_EXIT_LOG);
}
/// <summary>
/// Update the progressbar status message
/// </summary>
private void UpdateStatusBar()
{
log.Debug("UpdateStatusBar" + BaseModel.FUNCTION_ENTERED_LOG);
UpdateProgressbarStatus(string.Empty, false);
log.Debug("UpdateStatusBar" + BaseModel.FUNCTION_EXIT_LOG);
}
/// <summary>
/// CanLaunchAboutView
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
private bool CanLaunchAboutView(object obj)
{
return true;
}
/// <summary>
/// LaunchAboutView
/// </summary>
/// <param name="obj"></param>
private void LaunchAboutView(object obj)
{
Messenger.NotifyColleagues(MessengerMessages.LAUNCH_ABOUT_VIEW, "About View");
}
/// <summary>
/// CanLaunchReportAProblemView
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
private bool CanLaunchReportAProblemView(object obj)
{
return true;
}
/// <summary>
/// LaunchReportAProblemView
/// </summary>
/// <param name="obj"></param>
private void LaunchReportAProblemView(object obj)
{
Messenger.NotifyColleagues(MessengerMessages.LAUNCH_REPORT_A_PROBLEM_VIEW, "Report A Problem");
}
/// <summary>
/// </summary>
/// <param name = "obj"></param>
private void ExitFromApplication(object obj)
{
log.Debug(BaseModel.FUNCTION_ENTERED_LOG);
Messenger.NotifyColleagues(MessengerMessages.EXIT_APPLICATION, obj);
log.Debug(BaseModel.FUNCTION_EXIT_LOG);
}
# endregion
}
Code behing of my MainView (Where all the Views are Registered)
#region class - MainView
/// <summary>
/// Interaction logic for MainView.xaml
/// </summary>
public partial class MainView : BaseWindowClass
{
# region Member Variables
/// <summary>
/// log
/// </summary>
private static readonly ILog log = LogManager.GetLogger(typeof(MainView));
public readonly MainViewModel mainViewModel;
# endregion
# region Constructor
/// <summary>
/// Default Constuctor
/// </summary>
public MainView()
{
InitializeComponent();
mainViewModel = new MainViewModel();
mainViewModel.Messenger.UnRegister(this);
mainViewModel.Messenger.Register(this);
this.DataContext = mainViewModel;
}
# endregion
# region Protected Methods
/// <summary>
/// LaunchMenuConfigView
/// </summary>
/// <param name="menuConfigViewModel"></param>
[MessengerMessageSink(MessengerMessages.LAUNCH_VIEW_MENU_CONFIG, ParameterType = typeof(MenuConfigViewModel))]
protected void LaunchMenuConfigView(MenuConfigViewModel menuConfigViewModel)
{
log.Debug("LaunchMenuConfigView" + Utility.FUNCTION_ENTERED_LOG);
var menuConfigView = new MenuConfigView()
{
DataContext = menuConfigViewModel,
Owner =GetWindow(this),
};
menuConfigView.ShowDialog();
log.Debug("LaunchMenuConfigView" + Utility.FUNCTION_EXIT_LOG);
}
/// <summary>
/// LaunchNavigationKeyDetailsView
/// </summary>
/// <param name="obj"></param>
[MessengerMessageSink(MessengerMessages.LAUNCH_VIEW_NAVIGATIONKEY, ParameterType = typeof(UtilityViewModel))]
protected void LaunchNavigationKeyDetailsView(UtilityViewModel utilityViewModel)
{
log.Debug("LaunchNavigationKeyDetailsView" + Utility.FUNCTION_ENTERED_LOG);
var navigationScreen = new NavigationKeyDetailsView() {DataContext=utilityViewModel,Owner=GetWindow(this) };
navigationScreen.ShowDialog();
log.Debug("LaunchNavigationKeyDetailsView" + Utility.FUNCTION_EXIT_LOG);
}
/// <summary>
/// ReportProblemMenuItem_Click
/// </summary>
/// <param name="obj"></param>
[MessengerMessageSink(MessengerMessages.LAUNCH_ABOUT_VIEW,ParameterType=typeof(string))]
protected void LaunchABoutView(string obj)
{
log.Debug("LaunchABoutView" + Utility.FUNCTION_ENTERED_LOG);
var aboutScreen = new AboutDialog(Utility.TOOL_NAME,
Utility.TOOL_VERSION);
aboutScreen.ShowDialog();
log.Debug("LaunchABoutView" + Utility.FUNCTION_EXIT_LOG);
}
/// <summary>
/// ReportProblemMenuItem_Click
/// </summary>
/// <param name="obj"></param>
[MessengerMessageSink(MessengerMessages.LAUNCH_REPORT_A_PROBLEM_VIEW, ParameterType = typeof(string))]
protected void LaunchReportProblemView(string obj)
{
log.Debug("LaunchReportProblemView" + Utility.FUNCTION_ENTERED_LOG);
ReportProblemView objReportProblemView = new ReportProblemView
{
Owner = GetWindow(this)
};
objReportProblemView.ShowDialog();
log.Debug("LaunchReportProblemView" + Utility.FUNCTION_EXIT_LOG);
}
/// <summary>
/// FileSelectView
/// </summary>
/// <param name="passwordViewModel">ViewModel Instance of <c>PasswordView</c></param>
[MessengerMessageSink(MessengerMessages.LAUNCH_FILE_SELECT_VIEW,ParameterType=typeof(PasswordViewModel))]
protected void LaunchFileSelectView(PasswordViewModel passwordViewModel)
{
log.Debug("LaunchFileSelectView" + Utility.FUNCTION_ENTERED_LOG);
PasswordView passwordView = new PasswordView
{
DataContext = passwordViewModel,
Owner = GetWindow(this)
};
passwordView.ShowDialog();
log.Debug("LaunchFileSelectView" + Utility.FUNCTION_EXIT_LOG);
}
/// <summary>
/// Launch Ask Password
/// </summary>
/// <param name="changePasswordViewModel"></param>
[MessengerMessageSink(MessengerMessages.ASKFORPASSWORD, ParameterType = typeof(ChangePasswordViewModel))]
protected void LaunchAskPasswordView(ChangePasswordViewModel changePasswordViewModel)
{
log.Debug("LaunchChangePasswordView" + Utility.FUNCTION_ENTERED_LOG);
ChangePasswordView objChangePasswordView = new ChangePasswordView
{
DataContext =
changePasswordViewModel,
Owner = GetWindow(
this)
};
objChangePasswordView.ShowDialog();
log.Debug("LaunchChangePasswordView" + Utility.FUNCTION_EXIT_LOG);
}
/// <summary>
///
/// </summary>
/// <param name="selectionScreenViewModel"></param>
[MessengerMessageSink(MessengerMessages.LAUNCH_SELECTIONSCREEN_VIEW, ParameterType = typeof(SelectionScreenViewModel))]
protected void LaunchSelectionScreen(SelectionScreenViewModel selectionScreenViewModel)
{
SelectionScreenView selectionScreenView =
new SelectionScreenView
{
DataContext =
selectionScreenViewModel,
Owner =
GetWindow(this)
};
selectionScreenView.ShowDialog();
}
# endregion
# region Public Methods
/// <summary>
/// Exit Application
/// </summary>
/// <param name="obj"></param>
[MessengerMessageSink(MessengerMessages.EXIT_APPLICATION,ParameterType=typeof(object))]
public void ExitApplication(object obj)
{
this.Close();
}
#endregion
}
#endregion
Launching Views works otherwise perfect (Like launching through the click of a button) but it doesnot work when i try to launch if while loading ExecutionView.
I am totally stuck .... nothing is working i even tried using dispatcher but still the same error.......
What i am tryinh to do here is When i run my application ExecutionView is loaded in my Main View... in ExecutionViewModel i am Performing some checks to launch another window but i feel that my Execution View is not loaded yet so its giving that problem.... but how to solve it...
Thanks fo the help .... in advance :)
Stack Trace
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Window.ShowHelper(Object booleanBox)
at System.Windows.Window.Show()
at System.Windows.Window.ShowDialog()
at MyMenuTool.ViewLayer.MainView.LaunchFileSelectView(PasswordViewModel passwordViewModel) in C:\AD\MyMenuTool\Code\Working\MyMenu_VS2010\MyMenu\MyMenu\MainView.xaml.cs:line 134

How to sort TabItems in the TabControl

I have a collection of type Page with an Order property, I set ItemsSource property of a TabControl an ObservableCollection. What I need to whenever I changed the Order property of an Entity
the related TabItem go in the correct location.
WPF XAML :
<TabControl Grid.Row="1" ItemsSource="{Binding Pages.ListViewModels}" SelectedItem="{Binding Pages.Current}" >
<TabControl.ContentTemplate>
<DataTemplate>
<views:EditPageView />
</DataTemplate>
</TabControl.ContentTemplate>
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Header}"/>
</DataTemplate>
</TabControl.ItemTemplate>
</TabControl>
C# Codes:
public class QuestionPageSection : INotifyPropertyChanged
{
public virtual int Id { get; set; }
public virtual string Header { get; set; }
private int _Order;
public virtual int Order
{
get
{
return _Order;
}
set
{
_Order = value;
this.RaisePropertyChanged(() => this.Order , PropertyChanged);
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
I want to force TabControl to sort TabItems based on the Order property. So now I have these questoins:
Is there any way to do it declaratively?
Does TabControl have a SortColumn property?
Does TabItem have a TabOrder property?
Is there any type of collection that listen to its childs to automatically sort itself based on a property of childs??
Any other idea would be apperciated.
You simply need to sort the collection that your TabControl is bound to
I've always hated the fact that ObservableCollection doesn't have a built-in Sort method, so I usually use my own custom class that inherits from ObservableCollection
public class ObservableCollectionEx<T> : ObservableCollection<T>
{
public ObservableCollectionEx() : base() { }
public ObservableCollectionEx(List<T> l) : base(l) { }
public ObservableCollectionEx(IEnumerable<T> l) : base(l) { }
#region IndexOf
/// <summary>
/// Returns the index of the first object which meets the specified function
/// </summary>
/// <param name="keySelector">A bool function to compare each Item by</param>
/// <returns>The index of the first Item which matches the function</returns>
public int IndexOf(Func<T, bool> compareFunction)
{
return Items.IndexOf(Items.FirstOrDefault(compareFunction));
}
#endregion
#region Sorting
/// <summary>
/// Sorts the items of the collection in ascending order according to a key.
/// </summary>
/// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
/// <param name="keySelector">A function to extract a key from an item.</param>
public void Sort<TKey>(Func<T, TKey> keySelector)
{
InternalSort(Items.OrderBy(keySelector));
}
/// <summary>
/// Sorts the items of the collection in descending order according to a key.
/// </summary>
/// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
/// <param name="keySelector">A function to extract a key from an item.</param>
public void SortDescending<TKey>(Func<T, TKey> keySelector)
{
InternalSort(Items.OrderByDescending(keySelector));
}
/// <summary>
/// Sorts the items of the collection in ascending order according to a key.
/// </summary>
/// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
/// <param name="keySelector">A function to extract a key from an item.</param>
/// <param name="comparer">An <see cref="IComparer{T}"/> to compare keys.</param>
public void Sort<TKey>(Func<T, TKey> keySelector, IComparer<TKey> comparer)
{
InternalSort(Items.OrderBy(keySelector, comparer));
}
/// <summary>
/// Moves the items of the collection so that their orders are the same as those of the items provided.
/// </summary>
/// <param name="sortedItems">An <see cref="IEnumerable{T}"/> to provide item orders.</param>
private void InternalSort(IEnumerable<T> sortedItems)
{
var sortedItemsList = sortedItems.ToList();
foreach (var item in sortedItemsList)
{
Move(IndexOf(item), sortedItemsList.IndexOf(item));
}
}
#endregion
}
I can use it like this:
ListViewModels = GetListViewModels();
ListViewModels.Sort(p => p.Order);
You can sort you're ObservableCollection on the UI side by using CollectionViewSource. Here's a link with examples: http://msdn.microsoft.com/en-us/library/ms742542.aspx
Thanks Rachel, your solution gave me the clue, but still your solution is an answer because I can manually call the Sort method whenever I change the Order property, but I wanted to make it automatic. So I end up with a dynamic version of your code.
Based on the Rachel I approached to this solution.
public class ObservableCollectionEx<T> : ObservableCollection<T>
{
public ObservableCollectionEx() : base() { }
public ObservableCollectionEx(List<T> l) : base(l) { }
public ObservableCollectionEx(IEnumerable<T> l) : base(l) { }
Func<IEnumerable<T>,IEnumerable<T>> sortFunction;
Action reset;
#region IndexOf
/// <summary>
/// Returns the index of the first object which meets the specified function
/// </summary>
/// <param name="keySelector">A bool function to compare each Item by</param>
/// <returns>The index of the first Item which matches the function</returns>
public int IndexOf(Func<T , bool> compareFunction)
{
return Items.IndexOf(Items.FirstOrDefault(compareFunction));
}
#endregion IndexOf
#region Sorting
/// <summary>
/// Sorts the items of the collection in ascending order according to a key.
/// </summary>
/// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
/// <param name="keySelector">A function to extract a key from an item.</param>
public void SetSort<TKey>(Func<T , TKey> keySelector)
{
sortFunction = list => list.OrderBy(keySelector);
InternalSort();
reset = () => SetSort(keySelector);
}
/// <summary>
/// Sorts the items of the collection in descending order according to a key.
/// </summary>
/// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
/// <param name="keySelector">A function to extract a key from an item.</param>
public void SetSortDescending<TKey>(Func<T , TKey> keySelector)
{
sortFunction = list => list.OrderByDescending(keySelector);
InternalSort();
reset = () => SetSortDescending(keySelector);
}
/// <summary>
/// Sorts the items of the collection in ascending order according to a key.
/// </summary>
/// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
/// <param name="keySelector">A function to extract a key from an item.</param>
/// <param name="comparer">An <see cref="IComparer{T}"/> to compare keys.</param>
public void SetSort<TKey>(Func<T , TKey> keySelector , IComparer<TKey> comparer)
{
sortFunction = list => list.OrderBy(keySelector , comparer);
InternalSort();
reset = () => SetSort(keySelector , comparer);
}
/// <summary>
/// Sorts the items of the collection in descending order according to a key.
/// </summary>
/// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
/// <param name="keySelector">A function to extract a key from an item.</param>
/// <param name="comparer">An <see cref="IComparer{T}"/> to compare keys.</param>
public void SetSortDescending<TKey>(Func<T , TKey> keySelector , IComparer<TKey> comparer)
{
sortFunction = list => list.OrderByDescending(keySelector , comparer);
InternalSort();
reset = () => SetSortDescending(keySelector , comparer);
}
/// <summary>
/// Moves the items of the collection so that their orders are the same as those of the items provided.
/// </summary>
private void InternalSort()
{
UpdateTracking(null , Items.ToList());
}
private void MoveItemToItsLocation(T item)
{
var sortListCache = sortFunction(Items).ToList();
Move(IndexOf(item) , sortListCache.IndexOf(item));
}
#endregion Sorting
public void UpdateTracking(IEnumerable<T> oldItems , IEnumerable<T> newItems)
{
if (sortFunction == null) return;
PropertyChangedEventHandler changeTracker = (o , change) => { MoveItemToItsLocation((T)o); };
Action<T> attachChangeTracker = o => o.ExecuteOnCast<INotifyPropertyChanged>(x => x.PropertyChanged += changeTracker);
Action<T> detachChangeTracker = o => o.ExecuteOnCast<INotifyPropertyChanged>(x => x.PropertyChanged -= changeTracker);
var greeting = new[] { attachChangeTracker , MoveItemToItsLocation };
var farwell = new[] { detachChangeTracker };
oldItems.ForEach(detachChangeTracker);
newItems.ForEach(attachChangeTracker , MoveItemToItsLocation);
}
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
base.OnCollectionChanged(e);
switch (e.Action) {
case NotifyCollectionChangedAction.Add:
case NotifyCollectionChangedAction.Remove:
case NotifyCollectionChangedAction.Replace:
UpdateTracking(e.OldItems.SafeGet(x => x.Cast<T>()) , e.NewItems.SafeGet(x => x.Cast<T>()));
break;
case NotifyCollectionChangedAction.Reset:
UpdateTracking(Items.ToList() , null);
if (reset != null)
reset();
break;
default:
break;
}
}
}
I only made a little change to make it follow the changes in the underlying collection, so it will sort itself automatically after any changes made to underlying collection or any element in the underlying collection.

Is there a Threadsafe Observable collection in .NET 4?

Platform: WPF, .NET 4.0, C# 4.0
Problem: In the Mainwindow.xaml i have a ListBox bound to a Customer collection which is currently an ObservableCollection< Customer >.
ObservableCollection<Customer> c = new ObservableCollection<Customer>();
This collection can be updated via multiple sources, like FileSystem, WebService etc.
To allow parallel loading of Customers I have created a helper class
public class CustomerManager(ref ObsevableCollection<Customer> cust)
that internally spawns a new Task (from Parallel extensions library) for each customer Source and adds a new Customer instance to the customer collection object (passed by ref to its ctor).
The problem is that ObservableCollection< T> (or any collection for that matter) cannot be used from calls other than the UI thread and an exception is encountered:
"NotSupportedException – This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread."
I tried using the
System.Collections.Concurrent.ConcurrentBag<Customer>
collection but it doesnot implement INotifyCollectionChanged interface. Hence my WPF UI won't get updated automatically.
So, is there a collection class that implements both property/collection change notifications and also allows calls from other non-UI threads?
By my initial bing/googling, there is none provided out of the box.
Edit: I created my own collection that inherits from ConcurrentBag< Customer > and also implements the INotifyCollectionChanged interface. But to my surprise even after invoking it in separate tasks, the WPF UI hangs until the task is completed. Aren't the tasks supposed to be executed in parallel and not block the UI thread?
Thanks for any suggestions, in advance.
There are two possible approaches. The first would be to inherit from a concurrent collection and add INotifyCollectionChanged functionality, and the second would be to inherit from a collection that implements INotifyCollectionChanged and add concurrency support. I think it is far easier and safer to add INotifyCollectionChanged support to a concurrent collection. My suggestion is below.
It looks long but most of the methods just call the internal concurrent collection as if the caller were using it directly. The handful of methods that add or remove from the collection inject a call to a private method that raises the notification event on the dispatcher provided at construction, thus allowing the class to be thread safe but ensuring the notifications are raised on the same thread all the time.
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Windows.Threading;
namespace Collections
{
/// <summary>
/// Concurrent collection that emits change notifications on a dispatcher thread
/// </summary>
/// <typeparam name="T">The type of objects in the collection</typeparam>
[Serializable]
[ComVisible(false)]
[HostProtection(SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)]
public class ObservableConcurrentBag<T> : IProducerConsumerCollection<T>,
IEnumerable<T>, ICollection, IEnumerable
{
/// <summary>
/// The dispatcher on which event notifications will be raised
/// </summary>
private readonly Dispatcher dispatcher;
/// <summary>
/// The internal concurrent bag used for the 'heavy lifting' of the collection implementation
/// </summary>
private readonly ConcurrentBag<T> internalBag;
/// <summary>
/// Initializes a new instance of the ConcurrentBag<T> class that will raise <see cref="INotifyCollectionChanged"/> events
/// on the specified dispatcher
/// </summary>
public ObservableConcurrentBag(Dispatcher dispatcher)
{
this.dispatcher = dispatcher;
this.internalBag = new ConcurrentBag<T>();
}
/// <summary>
/// Initializes a new instance of the ConcurrentBag<T> class that contains elements copied from the specified collection
/// that will raise <see cref="INotifyCollectionChanged"/> events on the specified dispatcher
/// </summary>
public ObservableConcurrentBag(Dispatcher dispatcher, IEnumerable<T> collection)
{
this.dispatcher = dispatcher;
this.internalBag = new ConcurrentBag<T>(collection);
}
/// <summary>
/// Occurs when the collection changes
/// </summary>
public event NotifyCollectionChangedEventHandler CollectionChanged;
/// <summary>
/// Raises the <see cref="CollectionChanged"/> event on the <see cref="dispatcher"/>
/// </summary>
private void RaiseCollectionChangedEventOnDispatcher(NotifyCollectionChangedEventArgs e)
{
this.dispatcher.BeginInvoke(new Action<NotifyCollectionChangedEventArgs>(this.RaiseCollectionChangedEvent), e);
}
/// <summary>
/// Raises the <see cref="CollectionChanged"/> event
/// </summary>
/// <remarks>
/// This method must only be raised on the dispatcher - use <see cref="RaiseCollectionChangedEventOnDispatcher" />
/// to do this.
/// </remarks>
private void RaiseCollectionChangedEvent(NotifyCollectionChangedEventArgs e)
{
this.CollectionChanged(this, e);
}
#region Members that pass through to the internal concurrent bag but also raise change notifications
bool IProducerConsumerCollection<T>.TryAdd(T item)
{
bool result = ((IProducerConsumerCollection<T>)this.internalBag).TryAdd(item);
if (result)
{
this.RaiseCollectionChangedEventOnDispatcher(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item));
}
return result;
}
public void Add(T item)
{
this.internalBag.Add(item);
this.RaiseCollectionChangedEventOnDispatcher(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item));
}
public bool TryTake(out T item)
{
bool result = this.TryTake(out item);
if (result)
{
this.RaiseCollectionChangedEventOnDispatcher(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item));
}
return result;
}
#endregion
#region Members that pass through directly to the internal concurrent bag
public int Count
{
get
{
return this.internalBag.Count;
}
}
public bool IsEmpty
{
get
{
return this.internalBag.IsEmpty;
}
}
bool ICollection.IsSynchronized
{
get
{
return ((ICollection)this.internalBag).IsSynchronized;
}
}
object ICollection.SyncRoot
{
get
{
return ((ICollection)this.internalBag).SyncRoot;
}
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return ((IEnumerable<T>)this.internalBag).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)this.internalBag).GetEnumerator();
}
public T[] ToArray()
{
return this.internalBag.ToArray();
}
void IProducerConsumerCollection<T>.CopyTo(T[] array, int index)
{
((IProducerConsumerCollection<T>)this.internalBag).CopyTo(array, index);
}
void ICollection.CopyTo(Array array, int index)
{
((ICollection)this.internalBag).CopyTo(array, index);
}
#endregion
}
}
Please take a look at the BindableCollection<T> from Caliburn.Micro library:
/// <summary>
/// A base collection class that supports automatic UI thread marshalling.
/// </summary>
/// <typeparam name="T">The type of elements contained in the collection.</typeparam>
#if !SILVERLIGHT && !WinRT
[Serializable]
#endif
public class BindableCollection<T> : ObservableCollection<T>, IObservableCollection<T> {
/// <summary>
/// Initializes a new instance of the <see cref = "Caliburn.Micro.BindableCollection{T}" /> class.
/// </summary>
public BindableCollection() {
IsNotifying = true;
}
/// <summary>
/// Initializes a new instance of the <see cref = "Caliburn.Micro.BindableCollection{T}" /> class.
/// </summary>
/// <param name = "collection">The collection from which the elements are copied.</param>
/// <exception cref = "T:System.ArgumentNullException">
/// The <paramref name = "collection" /> parameter cannot be null.
/// </exception>
public BindableCollection(IEnumerable<T> collection) : base(collection) {
IsNotifying = true;
}
#if !SILVERLIGHT && !WinRT
[field: NonSerialized]
#endif
bool isNotifying; //serializator try to serialize even autogenerated fields
/// <summary>
/// Enables/Disables property change notification.
/// </summary>
#if !WinRT
[Browsable(false)]
#endif
public bool IsNotifying {
get { return isNotifying; }
set { isNotifying = value; }
}
/// <summary>
/// Notifies subscribers of the property change.
/// </summary>
/// <param name = "propertyName">Name of the property.</param>
#if WinRT || NET45
public virtual void NotifyOfPropertyChange([CallerMemberName]string propertyName = "") {
#else
public virtual void NotifyOfPropertyChange(string propertyName) {
#endif
if(IsNotifying)
Execute.OnUIThread(() => OnPropertyChanged(new PropertyChangedEventArgs(propertyName)));
}
/// <summary>
/// Raises a change notification indicating that all bindings should be refreshed.
/// </summary>
public void Refresh() {
Execute.OnUIThread(() => {
OnPropertyChanged(new PropertyChangedEventArgs("Count"));
OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
});
}
/// <summary>
/// Inserts the item to the specified position.
/// </summary>
/// <param name = "index">The index to insert at.</param>
/// <param name = "item">The item to be inserted.</param>
protected override sealed void InsertItem(int index, T item) {
Execute.OnUIThread(() => InsertItemBase(index, item));
}
/// <summary>
/// Exposes the base implementation of the <see cref = "InsertItem" /> function.
/// </summary>
/// <param name = "index">The index.</param>
/// <param name = "item">The item.</param>
/// <remarks>
/// Used to avoid compiler warning regarding unverifiable code.
/// </remarks>
protected virtual void InsertItemBase(int index, T item) {
base.InsertItem(index, item);
}
#if NET || WP8 || WinRT
/// <summary>
/// Moves the item within the collection.
/// </summary>
/// <param name="oldIndex">The old position of the item.</param>
/// <param name="newIndex">The new position of the item.</param>
protected sealed override void MoveItem(int oldIndex, int newIndex) {
Execute.OnUIThread(() => MoveItemBase(oldIndex, newIndex));
}
/// <summary>
/// Exposes the base implementation fo the <see cref="MoveItem"/> function.
/// </summary>
/// <param name="oldIndex">The old index.</param>
/// <param name="newIndex">The new index.</param>
/// <remarks>Used to avoid compiler warning regarding unverificable code.</remarks>
protected virtual void MoveItemBase(int oldIndex, int newIndex) {
base.MoveItem(oldIndex, newIndex);
}
#endif
/// <summary>
/// Sets the item at the specified position.
/// </summary>
/// <param name = "index">The index to set the item at.</param>
/// <param name = "item">The item to set.</param>
protected override sealed void SetItem(int index, T item) {
Execute.OnUIThread(() => SetItemBase(index, item));
}
/// <summary>
/// Exposes the base implementation of the <see cref = "SetItem" /> function.
/// </summary>
/// <param name = "index">The index.</param>
/// <param name = "item">The item.</param>
/// <remarks>
/// Used to avoid compiler warning regarding unverifiable code.
/// </remarks>
protected virtual void SetItemBase(int index, T item) {
base.SetItem(index, item);
}
/// <summary>
/// Removes the item at the specified position.
/// </summary>
/// <param name = "index">The position used to identify the item to remove.</param>
protected override sealed void RemoveItem(int index) {
Execute.OnUIThread(() => RemoveItemBase(index));
}
/// <summary>
/// Exposes the base implementation of the <see cref = "RemoveItem" /> function.
/// </summary>
/// <param name = "index">The index.</param>
/// <remarks>
/// Used to avoid compiler warning regarding unverifiable code.
/// </remarks>
protected virtual void RemoveItemBase(int index) {
base.RemoveItem(index);
}
/// <summary>
/// Clears the items contained by the collection.
/// </summary>
protected override sealed void ClearItems() {
Execute.OnUIThread(ClearItemsBase);
}
/// <summary>
/// Exposes the base implementation of the <see cref = "ClearItems" /> function.
/// </summary>
/// <remarks>
/// Used to avoid compiler warning regarding unverifiable code.
/// </remarks>
protected virtual void ClearItemsBase() {
base.ClearItems();
}
/// <summary>
/// Raises the <see cref = "E:System.Collections.ObjectModel.ObservableCollection`1.CollectionChanged" /> event with the provided arguments.
/// </summary>
/// <param name = "e">Arguments of the event being raised.</param>
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e) {
if (IsNotifying) {
base.OnCollectionChanged(e);
}
}
/// <summary>
/// Raises the PropertyChanged event with the provided arguments.
/// </summary>
/// <param name = "e">The event data to report in the event.</param>
protected override void OnPropertyChanged(PropertyChangedEventArgs e) {
if (IsNotifying) {
base.OnPropertyChanged(e);
}
}
/// <summary>
/// Adds the range.
/// </summary>
/// <param name = "items">The items.</param>
public virtual void AddRange(IEnumerable<T> items) {
Execute.OnUIThread(() => {
var previousNotificationSetting = IsNotifying;
IsNotifying = false;
var index = Count;
foreach(var item in items) {
InsertItemBase(index, item);
index++;
}
IsNotifying = previousNotificationSetting;
OnPropertyChanged(new PropertyChangedEventArgs("Count"));
OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
});
}
/// <summary>
/// Removes the range.
/// </summary>
/// <param name = "items">The items.</param>
public virtual void RemoveRange(IEnumerable<T> items) {
Execute.OnUIThread(() => {
var previousNotificationSetting = IsNotifying;
IsNotifying = false;
foreach(var item in items) {
var index = IndexOf(item);
if (index >= 0) {
RemoveItemBase(index);
}
}
IsNotifying = previousNotificationSetting;
OnPropertyChanged(new PropertyChangedEventArgs("Count"));
OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
});
}
/// <summary>
/// Called when the object is deserialized.
/// </summary>
/// <param name="c">The streaming context.</param>
[OnDeserialized]
public void OnDeserialized(StreamingContext c) {
IsNotifying = true;
}
/// <summary>
/// Used to indicate whether or not the IsNotifying property is serialized to Xml.
/// </summary>
/// <returns>Whether or not to serialize the IsNotifying property. The default is false.</returns>
public virtual bool ShouldSerializeIsNotifying() {
return false;
}
}
Source
PS. Just take in mind that this class use some other classes from Caliburn.Micro so that you could either copy/pase all dependencies by your-self - OR - if you are not using any other application frameworks - just reference the library binary and give it a chance.
I spent ages looking at all the solutions and none really fit what I needed, until I finally realized the problem: I didn't want a threadsafe list - I just wanted a non-threadsafe list that could be modified on any thread, but that notified changes on the UI thread.
(The reason for not wanting a threadsafe collection is the usual one - often you need to perform multiple operations, like "if it's not in the list, then add it" which threadsafe lists don't actually help with, so you want to control the locking yourself).
The solution turned out to be quite simple in concept and has worked well for me. Just create a new list class that implements IList<T> and INotifyCollectionChanged. Delegate all calls you need to an underlying implementation (e.g. a List<T>) and then call notifications on the UI thread where needed.
public class AlbumList : IList<Album>, INotifyCollectionChanged
{
private readonly IList<Album> _listImplementation = new List<Album>();
public event NotifyCollectionChangedEventHandler CollectionChanged;
private void OnChanged(NotifyCollectionChangedEventArgs e)
{
Application.Current?.Dispatcher.Invoke(DispatcherPriority.Render,
new Action(() => CollectionChanged?.Invoke(this, e)));
}
public void Add(Album item)
{
_listImplementation.Add(item);
OnChanged(new NotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction.Add, item));
}
public bool Remove(Album item)
{
int index = _listImplementation.IndexOf(item);
var removed = index >= 0;
if (removed)
{
_listImplementation.RemoveAt(index);
OnChanged(new NotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction.Remove, item, index));
}
return removed;
}
// ...snip...
}
There's a detailed explanation and an implementation here. It was written mainly for .NET 3.5 SP1 but it will still work in 4.0.
The primary target of this implementation is when the "real" list exists longer than the bindable view of it (eg. if it is bound in a window that the user can open and close). If the lifetimes are the other way around (eg. you're updating the list from a background worker that runs only when the window is open), then there are some simpler designs available.

Resources