Implement file explorer based on tree view with multiple selection - wpf

I`m beginner WPF. I developing a new project at my work and I need to insert a file explorer control with multiple selection.
The concept need to be similar to acronis file explorer: (Treeview with checkboxes)
Look at the left container, I need to implement something similar to this,
I habe searched alot through google and I saw lot of implementations but nothing wasn`t similar to this.
Because I don`t have alot experience in WPF it quite difficult for me to start.
Do you have some tips or similar projects which might help me do it?
My project based on MVVM DP.
Thanks

Remodelling the Treeview is very easy, you start with your collection that you want to bind to, i.e.
<Grid>
<TreeView ItemsSource="{Binding Folders}"/>
</Grid>
However you then need to define how to display the data you have bound to. I'm assuming that your items are just an IEnumerable (any list or array) of FolderViewModels and FileViewModels (both have a Name property), so now we need to say how to display those. You do that by defining a DataTemplate and since this is for a tree we use a HeirarchicalDataTemplate as that also defines subItems
<Grid.Resources>
<HierarchicalDataTemplate DataType="{x:Type viewModel:FolderViewModel}"
ItemsSource="{Binding SubFoldersAndFiles}">
<CheckBox Content="{Binding Name}"/>
</HierarchicalDataTemplate>
<Grid.Resources/>
Files are the same but dont need sub items
<HierarchicalDataTemplate DataType="{x:Type viewModel:FolderViewModel}">
<CheckBox Content="{Binding Name}"/>
</HierarchicalDataTemplate>
So putting it all together you get
<Grid>
<Grid.Resources>
<HierarchicalDataTemplate DataType="{x:Type viewModel:FolderViewModel}"
ItemsSource="{Binding SubFoldersAndFiles}">
<CheckBox Content="{Binding Name}"/>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type viewModel:FolderViewModel}">
<CheckBox Content="{Binding Name}"/>
</HierarchicalDataTemplate>
<Grid.Resources/>
<TreeView ItemsSource="{Binding Folders}"/>
</Grid>
Icons
If you want to show icons then you change the content in the CheckBox, I'm assuming you will define an Image on your ViewModel.
<CheckBox>
<CheckBox.Content>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Image}"/>
<TextBlock Text="{Binding Name}"/>
</StackPanel>
</CheckBox.Content>
Selection
Finally you have to handle the selection of items. I'd advise adding an IsSelected property to your FileViewModel and FolderViewModels. For files this is incredibly simple, its just a bool.
public class FileViewModel : INotifyProperty
...
public bool IsSelected //Something here to handle get/set and NotifyPropertyChanged that depends on your MVVM framework, I use ReactiveUI a lot so that's this syntax
{
get { return _IsSelected;}
set { this.RaiseAndSetIfChanged(x=>x.IsSelected, value); }
}
and
<CheckBox IsChecked="{Binding IsSelected}">
Its slightly more complicated with FolderViewModel and I'll look at the logic in a second. First the Xaml, just replace the current CheckBox declaration with
<CheckBox IsThreeState="True" IsChecked="{Binding IsSelected}">
<!--IsChecked = True, False or null-->
So now we need to return a set of Nullable<bool> (aka bool?).
public bool? IsSelected
{
get
{
if (SubFoldersAndFiles.All(x=>x.IsSelected) return true;
if (SubFoldersAndFiles.All(x=>x.IsSelected==false) return false;
return null;
}
set
{
// We can't set to indeterminate at folder level so we have to set to
// set to oposite of what we have now
if(value == null)
value = !IsSelected;
foreach(var x in SubFoldersAndFiles)
x.IsSelected = value;
}
Or something very similar...

After taking a look at the answer by #AlSki, I decided it is neither intuitive nor versatile enough for my liking and came up with my own solution. The disadvantage of using my solution, however, is it requires a tad bit more boilerplate. On the other hand, it offers a LOT more flexibility.
The samples below assume you use .NET 4.6.1 and C# 6.0.
/// <summary>
/// A base for abstract objects (implements INotifyPropertyChanged).
/// </summary>
[Serializable]
public abstract class AbstractObject : INotifyPropertyChanged
{
/// <summary>
///
/// </summary>
[field: NonSerialized()]
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
///
/// </summary>
/// <param name="propertyName"></param>
public void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
/// <summary>
///
/// </summary>
/// <typeparam name="TKind"></typeparam>
/// <param name="Source"></param>
/// <param name="NewValue"></param>
/// <param name="Names"></param>
protected virtual bool SetValue<TKind>(ref TKind Source, TKind NewValue, params string[] Notify)
{
//Set value if the new value is different from the old
if (!Source.Equals(NewValue))
{
Source = NewValue;
//Notify all applicable properties
Notify?.ForEach(i => OnPropertyChanged(i));
return true;
}
return false;
}
/// <summary>
///
/// </summary>
public AbstractObject()
{
}
}
An object with a check state.
/// <summary>
/// Specifies an object with a checked state.
/// </summary>
public interface ICheckable
{
/// <summary>
///
/// </summary>
bool? IsChecked
{
get; set;
}
}
/// <summary>
///
/// </summary>
public class CheckableObject : AbstractObject, ICheckable
{
/// <summary>
///
/// </summary>
[field: NonSerialized()]
public event EventHandler<EventArgs> Checked;
/// <summary>
///
/// </summary>
[field: NonSerialized()]
public event EventHandler<EventArgs> Unchecked;
/// <summary>
///
/// </summary>
[XmlIgnore]
protected bool? isChecked;
/// <summary>
///
/// </summary>
public virtual bool? IsChecked
{
get
{
return isChecked;
}
set
{
if (SetValue(ref isChecked, value, "IsChecked") && value != null)
{
if (value.Value)
{
OnChecked();
}
else OnUnchecked();
}
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override string ToString()
{
return base.ToString();
//return isChecked.ToString();
}
/// <summary>
///
/// </summary>
protected virtual void OnChecked()
{
Checked?.Invoke(this, new EventArgs());
}
/// <summary>
///
/// </summary>
protected virtual void OnUnchecked()
{
Unchecked?.Invoke(this, new EventArgs());
}
/// <summary>
///
/// </summary>
public CheckableObject() : base()
{
}
/// <summary>
///
/// </summary>
/// <param name="isChecked"></param>
public CheckableObject(bool isChecked = false)
{
IsChecked = isChecked;
}
}
The view model for checked system objects:
/// <summary>
///
/// </summary>
public class CheckableSystemObject : CheckableObject
{
#region Properties
/// <summary>
///
/// </summary>
public event EventHandler Collapsed;
/// <summary>
///
/// </summary>
public event EventHandler Expanded;
bool StateChangeHandled = false;
CheckableSystemObject Parent { get; set; } = default(CheckableSystemObject);
ISystemProvider SystemProvider { get; set; } = default(ISystemProvider);
ConcurrentCollection<CheckableSystemObject> children = new ConcurrentCollection<CheckableSystemObject>();
/// <summary>
///
/// </summary>
public ConcurrentCollection<CheckableSystemObject> Children
{
get
{
return children;
}
private set
{
SetValue(ref children, value, "Children");
}
}
bool isExpanded = false;
/// <summary>
///
/// </summary>
public bool IsExpanded
{
get
{
return isExpanded;
}
set
{
if (SetValue(ref isExpanded, value, "IsExpanded"))
{
if (value)
{
OnExpanded();
}
else OnCollapsed();
}
}
}
bool isSelected = false;
/// <summary>
///
/// </summary>
public bool IsSelected
{
get
{
return isSelected;
}
set
{
SetValue(ref isSelected, value, "IsSelected");
}
}
string path = string.Empty;
/// <summary>
///
/// </summary>
public string Path
{
get
{
return path;
}
set
{
SetValue(ref path, value, "Path");
}
}
bool queryOnExpanded = false;
/// <summary>
///
/// </summary>
public bool QueryOnExpanded
{
get
{
return queryOnExpanded;
}
set
{
SetValue(ref queryOnExpanded, value);
}
}
/// <summary>
///
/// </summary>
public override bool? IsChecked
{
get
{
return isChecked;
}
set
{
if (SetValue(ref isChecked, value, "IsChecked") && value != null)
{
if (value.Value)
{
OnChecked();
}
else OnUnchecked();
}
}
}
#endregion
#region CheckableSystemObject
/// <summary>
///
/// </summary>
/// <param name="path"></param>
/// <param name="systemProvider"></param>
/// <param name="isChecked"></param>
public CheckableSystemObject(string path, ISystemProvider systemProvider, bool? isChecked = false) : base()
{
Path = path;
SystemProvider = systemProvider;
IsChecked = isChecked;
}
#endregion
#region Methods
void Determine()
{
//If it has a parent, determine it's state by enumerating all children, but current instance, which is already accounted for.
if (Parent != null)
{
StateChangeHandled = true;
var p = Parent;
while (p != null)
{
p.IsChecked = Determine(p);
p = p.Parent;
}
StateChangeHandled = false;
}
}
bool? Determine(CheckableSystemObject Root)
{
//Whether or not all children and all children's children have the same value
var Uniform = true;
//If uniform, the value
var Result = default(bool?);
var j = false;
foreach (var i in Root.Children)
{
//Get first child's state
if (j == false)
{
Result = i.IsChecked;
j = true;
}
//If the previous child's state is not equal to the current child's state, it is not uniform and we are done!
else if (Result != i.IsChecked)
{
Uniform = false;
break;
}
}
return !Uniform ? null : Result;
}
void Query(ISystemProvider SystemProvider)
{
children.Clear();
if (SystemProvider != null)
{
foreach (var i in SystemProvider.Query(path))
{
children.Add(new CheckableSystemObject(i, SystemProvider, isChecked)
{
Parent = this
});
}
}
}
/// <summary>
///
/// </summary>
protected override void OnChecked()
{
base.OnChecked();
if (!StateChangeHandled)
{
//By checking the root only, all children are checked automatically
foreach (var i in children)
i.IsChecked = true;
Determine();
}
}
/// <summary>
///
/// </summary>
protected override void OnUnchecked()
{
base.OnUnchecked();
if (!StateChangeHandled)
{
//By unchecking the root only, all children are unchecked automatically
foreach (var i in children)
i.IsChecked = false;
Determine();
}
}
/// <summary>
///
/// </summary>
protected virtual void OnCollapsed()
{
Collapsed?.Invoke(this, new EventArgs());
}
/// <summary>
///
/// </summary>
protected virtual void OnExpanded()
{
Expanded?.Invoke(this, new EventArgs());
if (!children.Any<CheckableSystemObject>() || queryOnExpanded)
BeginQuery(SystemProvider);
}
/// <summary>
///
/// </summary>
/// <param name="SystemProvider"></param>
public async void BeginQuery(ISystemProvider SystemProvider)
{
await Task.Run(() => Query(SystemProvider));
}
#endregion
}
Utilities for querying system objects; note, by defining your own SystemProvider, you can query different types of systems (i.e., local or remote). By default, your local system is queried. If you want to display objects from a remote server like FTP, you'd want to define a SystemProvider that utilizes the appropriate web protocol.
/// <summary>
/// Specifies an object capable of querying system objects.
/// </summary>
public interface ISystemProvider
{
/// <summary>
///
/// </summary>
/// <param name="Path">The path to query.</param>
/// <param name="Source">A source used to make queries.</param>
/// <returns>A list of system object paths.</returns>
IEnumerable<string> Query(string Path, object Source = null);
}
/// <summary>
/// Defines base functionality for an <see cref="ISystemProvider"/>.
/// </summary>
public abstract class SystemProvider : ISystemProvider
{
/// <summary>
///
/// </summary>
/// <param name="Path"></param>
/// <param name="Source"></param>
/// <returns></returns>
public abstract IEnumerable<string> Query(string Path, object Source = null);
}
/// <summary>
/// Defines functionality to query a local system.
/// </summary>
public class LocalSystemProvider : SystemProvider
{
/// <summary>
///
/// </summary>
/// <param name="Path"></param>
/// <param name="Source"></param>
/// <returns></returns>
public override IEnumerable<string> Query(string Path, object Source = null)
{
if (Path.IsNullOrEmpty())
{
foreach (var i in System.IO.DriveInfo.GetDrives())
yield return i.Name;
}
else
{
if (System.IO.Directory.Exists(Path))
{
foreach (var i in System.IO.Directory.EnumerateFileSystemEntries(Path))
yield return i;
}
}
}
}
And then an inherited TreeView, which puts this all together:
/// <summary>
///
/// </summary>
public class SystemObjectPicker : TreeViewExt
{
#region Properties
/// <summary>
///
/// </summary>
public static DependencyProperty QueryOnExpandedProperty = DependencyProperty.Register("QueryOnExpanded", typeof(bool), typeof(SystemObjectPicker), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnQueryOnExpandedChanged));
/// <summary>
///
/// </summary>
public bool QueryOnExpanded
{
get
{
return (bool)GetValue(QueryOnExpandedProperty);
}
set
{
SetValue(QueryOnExpandedProperty, value);
}
}
static void OnQueryOnExpandedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
d.As<SystemObjectPicker>().OnQueryOnExpandedChanged((bool)e.NewValue);
}
/// <summary>
///
/// </summary>
public static DependencyProperty RootProperty = DependencyProperty.Register("Root", typeof(string), typeof(SystemObjectPicker), new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnRootChanged));
/// <summary>
///
/// </summary>
public string Root
{
get
{
return (string)GetValue(RootProperty);
}
set
{
SetValue(RootProperty, value);
}
}
static void OnRootChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
d.As<SystemObjectPicker>().OnRootChanged((string)e.NewValue);
}
/// <summary>
///
/// </summary>
static DependencyProperty SystemObjectsProperty = DependencyProperty.Register("SystemObjects", typeof(ConcurrentCollection<CheckableSystemObject>), typeof(SystemObjectPicker), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
/// <summary>
///
/// </summary>
ConcurrentCollection<CheckableSystemObject> SystemObjects
{
get
{
return (ConcurrentCollection<CheckableSystemObject>)GetValue(SystemObjectsProperty);
}
set
{
SetValue(SystemObjectsProperty, value);
}
}
/// <summary>
///
/// </summary>
public static DependencyProperty SystemProviderProperty = DependencyProperty.Register("SystemProvider", typeof(ISystemProvider), typeof(SystemObjectPicker), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnSystemProviderChanged));
/// <summary>
///
/// </summary>
public ISystemProvider SystemProvider
{
get
{
return (ISystemProvider)GetValue(SystemProviderProperty);
}
set
{
SetValue(SystemProviderProperty, value);
}
}
static void OnSystemProviderChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
d.As<SystemObjectPicker>().OnSystemProviderChanged((ISystemProvider)e.NewValue);
}
#endregion
#region SystemObjectPicker
/// <summary>
///
/// </summary>
public SystemObjectPicker() : base()
{
SetCurrentValue(SystemObjectsProperty, new ConcurrentCollection<CheckableSystemObject>());
SetCurrentValue(SystemProviderProperty, new LocalSystemProvider());
SetBinding(ItemsSourceProperty, new Binding()
{
Mode = BindingMode.OneWay,
Path = new PropertyPath("SystemObjects"),
Source = this
});
}
#endregion
#region Methods
void OnQueryOnExpandedChanged(CheckableSystemObject Item, bool Value)
{
foreach (var i in Item.Children)
{
i.QueryOnExpanded = Value;
OnQueryOnExpandedChanged(i, Value);
}
}
/// <summary>
///
/// </summary>
/// <param name="Value"></param>
protected virtual void OnQueryOnExpandedChanged(bool Value)
{
foreach (var i in SystemObjects)
OnQueryOnExpandedChanged(i, Value);
}
/// <summary>
///
/// </summary>
/// <param name="Provider"></param>
/// <param name="Root"></param>
protected virtual void OnRefreshed(ISystemProvider Provider, string Root)
{
SystemObjects.Clear();
if (Provider != null)
{
foreach (var i in Provider.Query(Root))
{
SystemObjects.Add(new CheckableSystemObject(i, SystemProvider)
{
QueryOnExpanded = QueryOnExpanded
});
}
}
}
/// <summary>
///
/// </summary>
/// <param name="Value"></param>
protected virtual void OnRootChanged(string Value)
{
OnRefreshed(SystemProvider, Value);
}
/// <summary>
///
/// </summary>
/// <param name="Value"></param>
protected virtual void OnSystemProviderChanged(ISystemProvider Value)
{
OnRefreshed(Value, Root);
}
#endregion
}
Obviously, it's dramatically more complex than #AlSki's answer, but, again, you get more flexibility and the hard stuff is taken care of for you already.
In addition, I have published this code in the latest version of my open source project (3.1) if such a thing interests you; if not, the samples above is all you need to get it working.
If you do not download the project, note the following:
You will find some extension methods that do not exist, which can be supplemented with their counterparts (e.g., IsNullOrEmpty extension is identical to string.IsNullOrEmpty()).
TreeViewExt is a custom TreeView I designed so if you don't care about that, simply change TreeViewExt to TreeView; either way, you should not have to define a special control template for it as it was designed to work with TreeView's existing facilities.
In the sample, I use my own version of a concurrent ObservableCollection; this is so you can query data on a background thread without jumping through hoops. Change this to ObservableCollection and make all queries synchronous OR use your own concurrent ObservableCollection to preserve the asynchronous functionality.
Finally, here is how you would use the control:
<Controls.Extended:SystemObjectPicker>
<Controls.Extended:SystemObjectPicker.ItemContainerStyle>
<Style TargetType="TreeViewItem" BasedOn="{StaticResource {x:Type TreeViewItem}}">
<Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</Style>
</Controls.Extended:SystemObjectPicker.ItemContainerStyle>
<Controls.Extended:SystemObjectPicker.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children, Mode=OneWay}">
<StackPanel Orientation="Horizontal">
<CheckBox
IsChecked="{Binding IsChecked, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Margin="0,0,5,0"/>
<TextBlock
Text="{Binding Path, Converter={StaticResource FileNameConverter}, Mode=OneWay}"/>
</StackPanel>
</HierarchicalDataTemplate>
</Controls.Extended:SystemObjectPicker.ItemTemplate>
</Controls.Extended:SystemObjectPicker>
To Do
Add a property to CheckableSystemObject that exposes a view model for the system object; that way, you can access the FileInfo/DirectoryInfo associated with it's path or some other source of data that otherwise describes it. If the object is remote, you may have already defined your own class to describe it, which could be useful if you have the reference to it.
Catch possible exceptions when querying a local system; if a system object cannot be accessed, it will fail. LocalSystemProvider also fails to address system paths that exceed 260 characters; however, that is beyond the scope of this project.
Note To Moderators
I referenced my own open source project for convenience as I published the above samples in the latest version; my intention is not to self-promote so if referencing your own project is frowned upon, I will proceed to remove the link.

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;
}
}

Sending Values from View To ViewModel

I have a senario here... (Extremely sorry writing such a long post)
I have are TreeView(Bound to the observable collection of Phones(Different types)) i have a contentCOntrol whose COntent Binding is set to the selectedItem for TreeView
Code....
<Border Grid.Column="2">
<ContentControl Name="userControlContentControl"
Content="{Binding ElementName=PhoneTreeViewUserControl,
Path=SelectedItem,
Converter={StaticResource ResourceKey=rightDisplayConverter}}">
<ContentControl.Resources>
<DataTemplate DataType="{x:Type EntityLayer:Settings}">
<ViewLayer:SettingsView />
</DataTemplate>
<DataTemplate DataType="{x:Type EntityLayer:CandyBarPhones}">
<ViewLayer:CandyBarPhonesListView />
</DataTemplate>
<DataTemplate DataType="{x:Type EntityLayer:CandyBarPhone}">
<ViewLayer:CandyBarPhoneView />
</DataTemplate>
<DataTemplate DataType="{x:Type EntityLayer:QwertyPhones}">
<ViewLayer:QwertyPhonesListView />
</DataTemplate>
<DataTemplate DataType="{x:Type EntityLayer:QuertyPhone}">
<ViewLayer:QuertyPhoneView />
</DataTemplate>
</ContentControl.Resources>
</ContentControl>
</Border>
Problem is that when i select a Phone from TreeView(a specific View is populated from contentcontrol) I wish to pass UniqueId(PhoneBase has that Property) to my ViewModel of View and also fire a function in viewModel so that it can get Data from BusinessLayer... and Initialize the ViewModel and all its Properties.
CodeBehind for UserControl
region class - QuertyPhoneView
/// <summary>
/// Interaction logic for ProductIdEditorView.xaml
/// </summary>
public partial class QuertyPhoneView : BaseUserControl
{
QertyPhoneViewModel quertyPhoneViewModel;
#region Constructor
/// <summary>
/// </summary>
public ProductIdEditorView()
{
InitializeComponent();
quertyPhoneViewModel =
new quertyPhoneViewModel ();
this.DataContext = quertyPhoneViewModel;
}
# endregion
}
#endregion
Also in ViewModel I have Messenger Registrations .... but Every time i selected another phone type and then select the former type the messenger are registered again without deregistering Earlier... (I dont have any Deregister method in Messenger, using Marlon's Mediator V2) and its making application Very Slow if used for an 15-20 min or so
ViewModel for a Typical View..
region class - QuertyPhoneViewModel
/// <summary>
/// QuertyPhoneViewModel
/// </summary>
public class QuertyPhoneViewModel : BaseViewModel
{
# region Member Variables
/// <summary>
/// quertyPhoneDetails
/// </summary>
private QuertyPhone quertyPhoneDetails;
/// <summary>
/// oldQuertyPhoneDetails
/// </summary>
private ProductId oldQuertyPhoneDetails;
/// <summary>
/// productIds
/// </summary>
private QuertyPhones quertyPhones;
/// <summary>
/// productIdModel
/// </summary>
private readonly QuertyPhoneModal quertyPhoneModal;
/// <summary>
/// log
/// </summary>
private static readonly ILog log =
LogManager.GetLogger(typeof (QuertyPhoneViewModel));
/// <summary>
/// selectedCalTblName
/// </summary>
private CalibrationTable selectedCalTblName;
# endregion
# region Constructor
/// <summary>
/// QuertyPhoneViewModel
/// </summary>
public QuertyPhoneViewModel()
{
RegisterForMessage();
quertyPhoneModal= new QuertyPhoneModal();
if (QuertyPhoneDetails == null)
{
//Requesting TreeViewUsersontrol To send Details
// I wish to remove these registrations
Messenger.NotifyColleagues<ProductId>(
MessengerMessages.SEND_SELECTED_PHONE, QuertyPhoneDetails);
}
CancelPhoneDetailsChangeCommand = new RelayCommand(CancelQuertyPhoneDetailsChanges,
obj => this.IsDirty);
SavePhoneDetailsChangeCommand = new RelayCommand(SaveQuertyPhoneDetailsToTree,
CanSaveQuertyPhoneDetailsToTree);
}
# endregion
# region Properties
/// <summary>
/// CalibrationTblNameList
/// </summary>
public ObservableCollection<CalibrationTable> CalibrationTblNameList { get; set; }
/// <summary>
/// CancelPhoneDetailsChangeCommand
/// </summary>
public ICommand CancelPhoneDetailsChangeCommand { get; set; }
/// <summary>
/// SavePhoneDetailsChangeCommand
/// </summary>
public ICommand SavePhoneDetailsChangeCommand { get; set; }
/// <summary>
/// QuertyPhoneDetails
/// </summary>
public ProductId QuertyPhoneDetails
{
get { return quertyPhoneDetails; }
set
{
quertyPhoneDetails = value;
OnPropertyChanged("QuertyPhoneDetails");
}
}
/// <summary>
/// SelectedCalTblName
/// </summary>
public CalibrationTable SelectedCalTblName
{
get { return selectedCalTblName; }
set
{
selectedCalTblName = value;
OnPropertyChanged("SelectedCalTblName");
if (selectedCalTblName != null)
{
QuertyPhoneDetails.CalibrationTableId =
selectedCalTblName.UniqueId;
}
}
}
/// <summary>
/// QuertyPhones
/// </summary>
public QuertyPhones QuertyPhones
{
get { return productIds; }
set
{
productIds = value;
OnPropertyChanged("QuertyPhones");
}
}
# endregion
# region Public Methods
# endregion
# region Private Methods
/// <summary>
/// RegisterForMessage
/// I wish to remove these registrations too
/// </summary>
private void RegisterForMessage()
{
log.Debug("RegisterForMessage" + BaseModel.FUNCTION_ENTERED_LOG);
Messenger.Register(MessengerMessages.RECIEVE_SELECTED_PHONE,
(Action<ProductId>) (o =>
{
if (o != null)
{
QuertyPhoneDetails
=
o.Clone() as
ProductId;
AttachChangeEvents
();
oldQuertyPhoneDetails
= o;
SetCalibrationTables
();
}
}));
Messenger.Register(MessengerMessages.REFRESH_PHONEDETILAS,
(Action<string>)
(o =>
{
GetOldQuertyPhoneDetails(o);
this.IsDirty = false;
}));
log.Debug("RegisterForMessage" + BaseModel.FUNCTION_EXIT_LOG);
}
/// <summary>
/// CanSaveQuertyPhoneDetailsToTree
/// </summary>
/// <param name = "obj"></param>
/// <returns></returns>
private bool CanSaveQuertyPhoneDetailsToTree(object obj)
{
return this.IsDirty && ValidateQuertyPhoneDetails();
}
/// <summary>
/// SaveQuertyPhoneDetailsToTree
/// </summary>
/// <param name = "obj"></param>
private void SaveQuertyPhoneDetailsToTree(object obj)
{
log.Debug("SaveQuertyPhoneDetails" + BaseModel.FUNCTION_ENTERED_LOG);
if (Utility.IsStringNullOrEmpty(QuertyPhoneDetails.CalibrationTableId))
{
MessageBoxResult result =
ShowMessageDialog(
"Calibration Table name is not set.Do you wish to proceed?",
"Save ProductId",
MessageBoxButton.YesNo,
MessageBoxImage.Exclamation);
if (result == MessageBoxResult.Yes)
{
SaveDetails();
}
}
else
{
SaveDetails();
}
log.Debug("SaveQuertyPhoneDetails" + BaseModel.FUNCTION_EXIT_LOG);
}
/// <summary>
/// SaveDetails
/// </summary>
private void SaveDetails()
{
log.Debug("SaveDetails" + BaseModel.FUNCTION_ENTERED_LOG);
if (productIdModel.SaveQuertyPhoneDetails(QuertyPhoneDetails))
{
UpdateProgressbarStatus(
"ProductId " + QuertyPhoneDetails.Specs
+ " saved successfully.",
false);
this.IsDirty = false;
}
else
{
ShowMessageDialog(
"ProductId " + QuertyPhoneDetails.Specs +
" not saved successfully.",
"Save ProductId",
MessageBoxButton.OK,
MessageBoxImage.Error);
UpdateProgressbarStatus(
"ProductId " + QuertyPhoneDetails.Specs
+ " not saved successfully.",
false);
}
log.Debug("SaveDetails" + BaseModel.FUNCTION_EXIT_LOG);
}
/// <summary>
/// SetCalibrationTables
/// </summary>
private void SetCalibrationTables()
{
log.Debug("SetCalibrationTables" + BaseModel.FUNCTION_ENTERED_LOG);
CalibrationTblNameList =
productIdModel.FileData.CalibrationTables.CalibrationTableList;
SelectedCalTblName = (CalibrationTblNameList.Where(
calibrationTable =>
calibrationTable.UniqueId.Equals(
QuertyPhoneDetails.CalibrationTableId))).FirstOrDefault();
log.Debug("SetCalibrationTables" + BaseModel.FUNCTION_EXIT_LOG);
}
/// <summary>
/// CancelQuertyPhoneDetailsChanges
/// </summary>
/// <param name = "obj"></param>
private void CancelQuertyPhoneDetailsChanges(object obj)
{
log.Debug("CancelQuertyPhoneDetailsChanges" + BaseModel.FUNCTION_ENTERED_LOG);
GetOldQuertyPhoneDetails(QuertyPhoneDetails.Specs);
this.IsDirty = false;
productIdModel.SelectMainProductList();
Messenger.NotifyColleagues<bool>(
MessengerMessages.POP_UP_CLOSE_REQUEST, true);
log.Debug("CancelQuertyPhoneDetailsChanges" + BaseModel.FUNCTION_EXIT_LOG);
}
/// <summary>
/// GetOldQuertyPhoneDetails
/// </summary>
/// <param name = "idNumber"></param>
private void GetOldQuertyPhoneDetails(string idNumber)
{
log.Debug("GetOldQuertyPhoneDetails" + BaseModel.FUNCTION_ENTERED_LOG);
if (!string.IsNullOrEmpty(idNumber))
{
ProductId tempQuertyPhoneDetails =
productIdModel.GetProduct(idNumber).Clone() as ProductId;
if (tempQuertyPhoneDetails != null)
{
QuertyPhoneDetails = tempQuertyPhoneDetails;
QuertyPhoneDetails.Reset();
}
AttachChangeEvents();
}
log.Debug("GetOldQuertyPhoneDetails" + BaseModel.FUNCTION_EXIT_LOG);
}
/// <summary>
/// AttachChangeEvents
/// </summary>
private void AttachChangeEvents()
{
log.Debug("AttachChangeEvents" + BaseModel.FUNCTION_ENTERED_LOG);
QuertyPhoneDetails.Reset();
QuertyPhoneDetails.PropertyChanged -= OnQuertyPhoneDetailsChanged;
QuertyPhoneDetails.PropertyChanged += OnQuertyPhoneDetailsChanged;
log.Debug("AttachChangeEvents" + BaseModel.FUNCTION_EXIT_LOG);
}
private void OnQuertyPhoneDetailsChanged(object sender,
PropertyChangedEventArgs e)
{
if (QuertyPhoneDetails.Changes.Count > 0)
{
OnItemDataChanged(sender, e, QuertyPhoneDetails.Changes.Count);
}
}
/// <summary>
/// ValidateQuertyPhoneDetails
/// </summary>
/// <returns></returns>
private bool ValidateQuertyPhoneDetails()
{
log.Debug("ValidateQuertyPhoneDetails" + BaseModel.FUNCTION_ENTERED_LOG);
if (
!Utility.IsValidAlphanumeric(
QuertyPhoneDetails.ControllerInformation)
||
(!Utility.IsValidAlphanumeric(QuertyPhoneDetails.PhoneId))
|| (!Utility.IsValidAlphanumeric(QuertyPhoneDetails.Specs)))
{
QuertyPhoneDetails.ErrorMsg =
AddTreeNodeViewModel.ERROR_NO_ALPHANUMERIC;
return false;
}
QuertyPhoneDetails.ErrorMsg = string.Empty;
log.Debug("ValidateQuertyPhoneDetails" + BaseModel.FUNCTION_EXIT_LOG);
return true;
}
# endregion
}
#endregion
I am absolutly Puzzled what to do...
ANy help in this regrad would be GR8!!! Thanks
Why not have your ParentViewModel track the SelectedItem instead of having your View do it? I personally hate doing any kind of business logic in my View. It should just be a pretty layer that sits on top of my ViewModels to make it easier for the user to interact with them.
For example, your PhonesViewModel might have:
// Leaving out get/set method details for simplicity
Observable<QuertyPhone> Phones { get; set; }
QuertyPhone SelectedPhone { get; set; }
ICommand SaveSelectedPhoneCommand { get; }
ICommand CancelSelectedPhoneCommand { get; }
Your View would simply look something like this:
<DockPanel>
<TreeView DockPanel.Dock="Left"
ItemsSource="{Binding Phones}"
SelectedItem="{Binding SelectedPhone}" />
<StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal">
<Button Content="{Binding SaveCommand}" />
<Button Content="{Binding CancelCommand}" />
</StackPanel>
<ContentControl Content="{Binding SelectedPhone} />
</DockPanel>
I would leave the validation in your QuertyPhone model, but would move the data access to the ViewModel. In my opinion, your models should just be dumb data objects. You also only have to register for messaging in a single place (your ViewModel), and if you need to do anything when the SelectedPhone changes, simply do it in the PropertyChanged event.
As a side note, I forget if you can bind a TreeView's SelectedItem or not, but if not you can either use a ListBox styled to look like a TreeView, or in the past I've added IsSelected properties to my TreeView data objects, and bound the TreeViewItem.IsSelected property to that.

How to attach FrameworkContentElement to MVVM Light EventToCommand

I'm trying to convert an event to a command on a devexpress wpf grid context menu item which is derived from FrameworkContentElement instead of FrameworkElement. This causes a runtime error :
{"Cannot attach type \"EventToCommand\" to type \"BarButtonItem\". Instances of type \"EventToCommand\" can only be attached to objects of type \"FrameworkElement\"."}
Is there any workaround?
<dxg:TableView.RowCellMenuCustomizations>
<dxb:BarButtonItem Name="deleteRowItem" Content="Delete" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="ItemClick">
<cmd:EventToCommand Command="{Binding FooChangeCommand}"
PassEventArgsToCommand="True" />
</i:EventTrigger>
</i:Interaction.Triggers>
</dxb:BarButtonItem>
<!--ItemClick="deleteRowItem_ItemClick"/>-->
</dxg:TableView.RowCellMenuCustomizations>
Unfortunately devexpress have run into problems changing the base class to FrameworkElement having intended to make that change...
The FrameworkConentElement is a class that is only available in WPF and not in Silverlight. As MVVM Light is intended to provide a common functionality for all WPF dialects (WPF 3.5, WPF 4, Silverlight 3, Silverlight 4, Sivlverlight 5, WP 7, WP 7.1) it cannot include an implementation that only works in one of the frameworks.
For a discussion about the differences between FrameworkElement and FrameworkContentElement see here.
However, you can just easily implement your own EventToCommand class supporting ContentElement (from which FrameworkContentElement inherits). The class was copied from BL0015 of the MVVM Light source code and modified:
using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;
namespace GalaSoft.MvvmLight.Command
{
/// <summary>
/// This <see cref="System.Windows.Interactivity.TriggerAction" /> can be
/// used to bind any event on any FrameworkElement to an <see cref="ICommand" />.
/// Typically, this element is used in XAML to connect the attached element
/// to a command located in a ViewModel. This trigger can only be attached
/// to a FrameworkElement or a class deriving from FrameworkElement.
/// <para>To access the EventArgs of the fired event, use a RelayCommand<EventArgs>
/// and leave the CommandParameter and CommandParameterValue empty!</para>
/// </summary>
////[ClassInfo(typeof(EventToCommand),
//// VersionString = "3.0.0.0",
//// DateString = "201003041420",
//// Description = "A Trigger used to bind any event to an ICommand.",
//// UrlContacts = "http://stackoverflow.com/q/6955785/266919",
//// Email = "")]
public partial class EventToCommandWpf : TriggerAction<DependencyObject>
{
/// <summary>
/// Gets or sets a value indicating whether the EventArgs passed to the
/// event handler will be forwarded to the ICommand's Execute method
/// when the event is fired (if the bound ICommand accepts an argument
/// of type EventArgs).
/// <para>For example, use a RelayCommand<MouseEventArgs> to get
/// the arguments of a MouseMove event.</para>
/// </summary>
public bool PassEventArgsToCommand
{
get;
set;
}
/// <summary>
/// Provides a simple way to invoke this trigger programatically
/// without any EventArgs.
/// </summary>
public void Invoke()
{
Invoke(null);
}
/// <summary>
/// Executes the trigger.
/// <para>To access the EventArgs of the fired event, use a RelayCommand<EventArgs>
/// and leave the CommandParameter and CommandParameterValue empty!</para>
/// </summary>
/// <param name="parameter">The EventArgs of the fired event.</param>
protected override void Invoke(object parameter)
{
if (AssociatedElementIsDisabled())
{
return;
}
var command = GetCommand();
var commandParameter = CommandParameterValue;
if (commandParameter == null
&& PassEventArgsToCommand)
{
commandParameter = parameter;
}
if (command != null
&& command.CanExecute(commandParameter))
{
command.Execute(commandParameter);
}
}
private static void OnCommandChanged(
EventToCommandWpf element,
DependencyPropertyChangedEventArgs e)
{
if (element == null)
{
return;
}
if (e.OldValue != null)
{
((ICommand)e.OldValue).CanExecuteChanged -= element.OnCommandCanExecuteChanged;
}
var command = (ICommand)e.NewValue;
if (command != null)
{
command.CanExecuteChanged += element.OnCommandCanExecuteChanged;
}
element.EnableDisableElement();
}
private bool AssociatedElementIsDisabled()
{
var element = GetAssociatedObject();
return AssociatedObject == null
|| (element != null
&& !element.IsEnabled);
}
private void EnableDisableElement()
{
var element = GetAssociatedObject();
if (element == null)
{
return;
}
var command = this.GetCommand();
if (this.MustToggleIsEnabledValue
&& command != null)
{
SetIsEnabled(element, command.CanExecute(this.CommandParameterValue));
}
}
private void OnCommandCanExecuteChanged(object sender, EventArgs e)
{
EnableDisableElement();
}
/// <summary>
/// Identifies the <see cref="CommandParameter" /> dependency property
/// </summary>
public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register(
"CommandParameter",
typeof(object),
typeof(EventToCommandWpf),
new PropertyMetadata(
null,
(s, e) => {
var sender = s as EventToCommandWpf;
if (sender == null)
{
return;
}
if (sender.AssociatedObject == null)
{
return;
}
sender.EnableDisableElement();
}));
/// <summary>
/// Identifies the <see cref="Command" /> dependency property
/// </summary>
public static readonly DependencyProperty CommandProperty = DependencyProperty.Register(
"Command",
typeof(ICommand),
typeof(EventToCommandWpf),
new PropertyMetadata(
null,
(s, e) => OnCommandChanged(s as EventToCommandWpf, e)));
/// <summary>
/// Identifies the <see cref="MustToggleIsEnabled" /> dependency property
/// </summary>
public static readonly DependencyProperty MustToggleIsEnabledProperty = DependencyProperty.Register(
"MustToggleIsEnabled",
typeof(bool),
typeof(EventToCommandWpf),
new PropertyMetadata(
false,
(s, e) => {
var sender = s as EventToCommandWpf;
if (sender == null)
{
return;
}
if (sender.AssociatedObject == null)
{
return;
}
sender.EnableDisableElement();
}));
private object _commandParameterValue;
private bool? _mustToggleValue;
/// <summary>
/// Gets or sets the ICommand that this trigger is bound to. This
/// is a DependencyProperty.
/// </summary>
public ICommand Command
{
get
{
return (ICommand)GetValue(CommandProperty);
}
set
{
SetValue(CommandProperty, value);
}
}
/// <summary>
/// Gets or sets an object that will be passed to the <see cref="Command" />
/// attached to this trigger. This is a DependencyProperty.
/// </summary>
public object CommandParameter
{
get
{
return this.GetValue(CommandParameterProperty);
}
set
{
SetValue(CommandParameterProperty, value);
}
}
/// <summary>
/// Gets or sets an object that will be passed to the <see cref="Command" />
/// attached to this trigger. This property is here for compatibility
/// with the Silverlight version. This is NOT a DependencyProperty.
/// For databinding, use the <see cref="CommandParameter" /> property.
/// </summary>
public object CommandParameterValue
{
get
{
return this._commandParameterValue ?? this.CommandParameter;
}
set
{
_commandParameterValue = value;
EnableDisableElement();
}
}
/// <summary>
/// Gets or sets a value indicating whether the attached element must be
/// disabled when the <see cref="Command" /> property's CanExecuteChanged
/// event fires. If this property is true, and the command's CanExecute
/// method returns false, the element will be disabled. If this property
/// is false, the element will not be disabled when the command's
/// CanExecute method changes. This is a DependencyProperty.
/// </summary>
public bool MustToggleIsEnabled
{
get
{
return (bool)this.GetValue(MustToggleIsEnabledProperty);
}
set
{
SetValue(MustToggleIsEnabledProperty, value);
}
}
/// <summary>
/// Gets or sets a value indicating whether the attached element must be
/// disabled when the <see cref="Command" /> property's CanExecuteChanged
/// event fires. If this property is true, and the command's CanExecute
/// method returns false, the element will be disabled. This property is here for
/// compatibility with the Silverlight version. This is NOT a DependencyProperty.
/// For databinding, use the <see cref="MustToggleIsEnabled" /> property.
/// </summary>
public bool MustToggleIsEnabledValue
{
get
{
return this._mustToggleValue == null
? this.MustToggleIsEnabled
: this._mustToggleValue.Value;
}
set
{
_mustToggleValue = value;
EnableDisableElement();
}
}
/// <summary>
/// Called when this trigger is attached to a DependencyObject.
/// </summary>
protected override void OnAttached()
{
base.OnAttached();
EnableDisableElement();
}
/// <summary>
/// This method is here for compatibility
/// with the Silverlight version.
/// </summary>
/// <returns>The object to which this trigger
/// is attached casted as a FrameworkElement.</returns>
private IInputElement GetAssociatedObject()
{
return AssociatedObject as IInputElement;
}
private void SetIsEnabled(IInputElement element, bool value)
{
if (element is UIElement)
{
((UIElement)element).IsEnabled = value;
}
else if (element is ContentElement)
{
((ContentElement)element).IsEnabled = value;
}
else
{
throw new InvalidOperationException("Cannot set IsEnabled. Element is neither ContentElemen, nor UIElement.");
}
}
/// <summary>
/// This method is here for compatibility
/// with the Silverlight version.
/// </summary>
/// <returns>The command that must be executed when
/// this trigger is invoked.</returns>
private ICommand GetCommand()
{
return Command;
}
}
}
To inlcude it into your code you have to define a xml namespace pointing to the correct dll and then use it just like the normal EventToCommand class.
NOTE: This class does not work in Silverlight!
For those trying to solve this specific issue using dev express, this will do the trick!
<dxg:TableView.RowCellMenuCustomizations>
<dxb:BarButtonItem Name="deleteRowItem" Content="Delete" Command="{Binding View.DataContext.DeleteSelectionCommand}" />
</dxg:TableView.RowCellMenuCustomizations>
I was following their example which had an event on the button, little realising there was also a command I could use. Then the challenge was working out the binding as the menu item is not on the main visual tree. However the above solves that.
I found this to work with DEV express
<dxb:BarButtonItem Content="123" Name="item1">
<dxmvvm:Interaction.Triggers>
<dxmvvm:EventToCommand EventName="ItemClick" Command="{Binding SomeCommand}" CommandParameter="{Binding ElementName=item1, Path=Content}"/>
</dxmvvm:Interaction.Triggers>
</dxb:BarButtonItem>

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.

Is it possible to use Binding in a DataGridTemplateColumn property

It seems like no matter what i do, i get AG_E_PARSER_PROPERTY_NOT_FOUND when trying to bind a property in DataGridTemplateColumn in silverlight. I've even tried tried the following
<data:DataGridTemplateColumn dataBehaviors:DataGridColumnBehaviors.BindableTextOverride="{Binding ElementName=LayoutRoot,
Path=DataContext.ColumnOneName}">
<data:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" />
</DataTemplate>
</data:DataGridTemplateColumn.CellTemplate>
<data:DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Text="{Binding Name, Mode=TwoWay}" />
</DataTemplate>
</data:DataGridTemplateColumn.CellEditingTemplate>
</data:DataGridTemplateColumn>
But no luck... I know the DataGridTemplateColumn does not contain a DataContext, but i don't feel like this should be the cause of the problem when I'm giving it the element and path to bind to. Any ideas?
Turns out the only way to get this to work is to implement it like DataGridBoundColumn. The idea is to bind to the binding property. This property will internally set the binding to a private DependencyProperty. When that property changes, you can perform anything needed inside the DependencyProperty Change Callback.
Here is an example:
/// <summary>
/// Represents a System.Windows.Controls.DataGrid column that can bind to a property
/// in the grid's data source. This class provides bindable properties ending with the suffix Binding.
/// These properties will affect the properties with the same name without the suffix
/// </summary>
public class DataGridBindableTemplateColumn : DataGridBoundColumn
{
/// <summary>
/// Identifies the DataGridBindableTemplateColumn.HeaderValueProperty dependency property
/// </summary>
internal static readonly DependencyProperty HeaderValueProperty =
DependencyProperty.Register("HeaderValue", typeof(object), typeof(DataGridBindableTemplateColumn),
new PropertyMetadata(null, OnHeaderValuePropertyChanged));
/// <summary>
/// Identifies the DataGridBindableTemplateColumn.VisibilityValueProperty dependency property
/// </summary>
internal static readonly DependencyProperty VisibilityValueProperty =
DependencyProperty.Register("VisibilityValue", typeof(Visibility), typeof(DataGridBindableTemplateColumn),
new PropertyMetadata(Visibility.Visible, OnVisibilityPropertyPropertyChanged));
/// <summary>
/// The callback the fires when the VisibilityValueProperty value changes
/// </summary>
/// <param name="d">The DependencyObject from which the property changed</param>
/// <param name="e">The DependencyPropertyChangedEventArgs containing the old and new value for the depenendency property that changed.</param>
private static void OnVisibilityPropertyPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DataGridBindableTemplateColumn sender = d as DataGridBindableTemplateColumn;
if (sender != null)
{
sender.OnVisibilityPropertyChanged((Visibility)e.OldValue, (Visibility)e.NewValue);
}
}
/// <summary>
/// The callback the fires when the HeaderValueProperty value changes
/// </summary>
/// <param name="d">The DependencyObject from which the property changed</param>
/// <param name="e">The DependencyPropertyChangedEventArgs containing the old and new value for the depenendency property that changed.</param>
private static void OnHeaderValuePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DataGridBindableTemplateColumn sender = d as DataGridBindableTemplateColumn;
if (sender != null)
{
sender.OnHeaderValueChanged((object)e.OldValue, (object)e.NewValue);
}
}
private Binding _headerBinding;
private Binding _visibilityBinding;
private DataTemplate _cellEditingTemplate;
private DataTemplate _cellTemplate;
/// <summary>
/// Gets and sets the Binding object used to bind to the Header property
/// </summary>
public Binding HeaderBinding
{
get { return _headerBinding; }
set
{
if (_headerBinding != value)
{
_headerBinding = value;
if (_headerBinding != null)
{
_headerBinding.ValidatesOnExceptions = false;
_headerBinding.NotifyOnValidationError = false;
BindingOperations.SetBinding(this, HeaderValueProperty, _headerBinding);
}
}
}
}
/// <summary>
/// Gets and sets the Binding object used to bind to the Visibility property
/// </summary>
public Binding VisibilityBinding
{
get { return _visibilityBinding; }
set
{
if (_visibilityBinding != value)
{
_visibilityBinding = value;
if (_visibilityBinding != null)
{
_visibilityBinding.ValidatesOnExceptions = false;
_visibilityBinding.NotifyOnValidationError = false;
BindingOperations.SetBinding(this, VisibilityValueProperty, _visibilityBinding);
}
}
}
}
/// <summary>
/// Gets or sets the template that is used to display the contents of a cell
/// that is in editing mode.
/// </summary>
public DataTemplate CellEditingTemplate
{
get { return _cellEditingTemplate; }
set
{
if (_cellEditingTemplate != value)
{
_cellEditingTemplate = value;
}
}
}
/// <summary>
/// Gets or sets the template that is used to display the contents of a cell
/// that is not in editing mode.
/// </summary>
public DataTemplate CellTemplate
{
get { return _cellTemplate; }
set
{
if (_cellTemplate != value)
{
_cellTemplate = value;
}
}
}
/// <summary>
///
/// </summary>
/// <param name="editingElement"></param>
/// <param name="uneditedValue"></param>
protected override void CancelCellEdit(FrameworkElement editingElement, object uneditedValue)
{
editingElement = GenerateEditingElement(null, null);
}
/// <summary>
///
/// </summary>
/// <param name="cell"></param>
/// <param name="dataItem"></param>
/// <returns></returns>
protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem)
{
if (CellEditingTemplate != null)
{
return (CellEditingTemplate.LoadContent() as FrameworkElement);
}
if (CellTemplate != null)
{
return (CellTemplate.LoadContent() as FrameworkElement);
}
if (!DesignerProperties.IsInDesignTool)
{
throw new Exception(string.Format("Missing template for type '{0}'", typeof(DataGridBindableTemplateColumn)));
}
return null;
}
/// <summary>
///
/// </summary>
/// <param name="cell"></param>
/// <param name="dataItem"></param>
/// <returns></returns>
protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
{
if (CellTemplate != null)
{
return (CellTemplate.LoadContent() as FrameworkElement);
}
if (CellEditingTemplate != null)
{
return (CellEditingTemplate.LoadContent() as FrameworkElement);
}
if (!DesignerProperties.IsInDesignTool)
{
throw new Exception(string.Format("Missing template for type '{0}'", typeof(DataGridBindableTemplateColumn)));
}
return null;
}
/// <summary>
///
/// </summary>
/// <param name="editingElement"></param>
/// <param name="editingEventArgs"></param>
/// <returns></returns>
protected override object PrepareCellForEdit(FrameworkElement editingElement, RoutedEventArgs editingEventArgs)
{
return null;
}
/// <summary>
///
/// </summary>
/// <param name="oldValue"></param>
/// <param name="newValue"></param>
protected virtual void OnHeaderValueChanged(object oldValue, object newValue)
{
Header = newValue;
}
/// <summary>
/// I'm to lazy to write a comment
/// </summary>
/// <param name="oldValue"></param>
/// <param name="newValue"></param>
protected virtual void OnVisibilityPropertyChanged(Visibility oldValue, Visibility newValue)
{
Visibility = newValue;
}
}
XAML:
<data:DataGridBindableTemplateColumn HeaderBinding="{Binding HeaderOne, Source={StaticResource ViewModel}}"
VisibilityBinding="{Binding HeaderOneVisibility, Source={StaticResource ViewMode}}"
HeaderStyle="{StaticResource DataColumnStyle}"
MinWidth="58">
...
</data:DataGridBindableTemplateColumn>
Hope this helps anyone with the same issue... Enjoy!

Resources