WPF. Find control that binds to specific property - wpf

Any ideas on how to implement a method that given a propertyname, finds a control (perhaps from a visualtree) which is bound to the given property?

Try this one. First, copy-paste this DependencyObjectHelper class in your project. It has a function that allows you to get all the BindingObjects in a given object.
public static class DependencyObjectHelper
{
public static List<BindingBase> GetBindingObjects(Object element)
{
List<BindingBase> bindings = new List<BindingBase>();
List<DependencyProperty> dpList = new List<DependencyProperty>();
dpList.AddRange(DependencyObjectHelper.GetDependencyProperties(element));
dpList.AddRange(DependencyObjectHelper.GetAttachedProperties(element));
foreach (DependencyProperty dp in dpList)
{
BindingBase b = BindingOperations.GetBindingBase(element as DependencyObject, dp);
if (b != null)
{
bindings.Add(b);
}
}
return bindings;
}
public static List<DependencyProperty> GetDependencyProperties(Object element)
{
List<DependencyProperty> properties = new List<DependencyProperty>();
MarkupObject markupObject = MarkupWriter.GetMarkupObjectFor(element);
if (markupObject != null)
{
foreach (MarkupProperty mp in markupObject.Properties)
{
if (mp.DependencyProperty != null)
{
properties.Add(mp.DependencyProperty);
}
}
}
return properties;
}
public static List<DependencyProperty> GetAttachedProperties(Object element)
{
List<DependencyProperty> attachedProperties = new List<DependencyProperty>();
MarkupObject markupObject = MarkupWriter.GetMarkupObjectFor(element);
if (markupObject != null)
{
foreach (MarkupProperty mp in markupObject.Properties)
{
if (mp.IsAttached)
{
attachedProperties.Add(mp.DependencyProperty);
}
}
}
return attachedProperties;
}
}
Then, create this GetBindingSourcesRecursive function. It recursively collects the DependencyObjects in the visual tree that has at least one Binding object targetting a given property name.
private void GetBindingSourcesRecursive(string propertyName, DependencyObject root, List<object> sources)
{
List<BindingBase> bindings = DependencyObjectHelper.GetBindingObjects(root);
Predicate<Binding> condition =
(b) =>
{
return (b.Path is PropertyPath)
&& (((PropertyPath)b.Path).Path == propertyName)
&& (!sources.Contains(root));
};
foreach (BindingBase bindingBase in bindings)
{
if (bindingBase is Binding)
{
if (condition(bindingBase as Binding))
sources.Add(root);
}
else if (bindingBase is MultiBinding)
{
MultiBinding mb = bindingBase as MultiBinding;
foreach (Binding b in mb.Bindings)
{
if (condition(bindingBase as Binding))
sources.Add(root);
}
}
else if (bindingBase is PriorityBinding)
{
PriorityBinding pb = bindingBase as PriorityBinding;
foreach (Binding b in pb.Bindings)
{
if (condition(bindingBase as Binding))
sources.Add(root);
}
}
}
int childrenCount = VisualTreeHelper.GetChildrenCount(root);
if (childrenCount > 0)
{
for (int i = 0; i < childrenCount; i++)
{
DependencyObject child = VisualTreeHelper.GetChild(root, i);
GetBindingSourcesRecursive(propertyName, child, sources);
}
}
}
Then, to use this, just call GetBindingsRecursive passing in the property name, the root visual (e.g. the Window), and an object list that will contain the results.
List<object> sources = new List<object>();
GetBindingSourcesRecursive("SomePropertyPath", this, sources);
sources.ForEach((o) => Console.WriteLine(o.ToString()));
Hope this helps.

I created code based on accepted ASanch answer. This code uses LogicalTreeHelper which makes it 6times faster (130ms vs 20ms when looking for control with specific binding on simple window).
Plus I fix some errors in ASanch code (look at original "else if (bindingBase is MultiBinding)" or "else if (bindingBase is PriorityBinding)").
public static class DependencyObjectHelper
{
/// <summary>
/// Gets all dependency objects which has binding to specific property
/// </summary>
/// <param name="dependencyObject"></param>
/// <param name="propertyName"></param>
/// <returns></returns>
public static IList<DependencyObject> GetDependencyObjectsWithBindingToProperty(DependencyObject dependencyObject, string propertyName)
{
var list = new List<DependencyObject>();
GetDependencyObjectsWithBindingToPropertyRecursive(propertyName, dependencyObject, list);
return list;
}
/// <summary>
///
/// </summary>
/// <param name="propertyName"></param>
/// <param name="dependencyObject"></param>
/// <param name="sources"></param>
/// <remarks>
/// Based on ASanch answer on http://stackoverflow.com/questions/3959421/wpf-find-control-that-binds-to-specific-property
/// </remarks>>
private static void GetDependencyObjectsWithBindingToPropertyRecursive(string propertyName, DependencyObject dependencyObject, ICollection<DependencyObject> sources)
{
var dependencyProperties = new List<DependencyProperty>();
dependencyProperties.AddRange(MarkupWriter.GetMarkupObjectFor(dependencyObject).Properties.Where(x => x.DependencyProperty != null).Select(x => x.DependencyProperty).ToList());
dependencyProperties.AddRange(
MarkupWriter.GetMarkupObjectFor(dependencyObject).Properties.Where(x => x.IsAttached && x.DependencyProperty != null).Select(x => x.DependencyProperty).ToList());
var bindings = dependencyProperties.Select(x => BindingOperations.GetBindingBase(dependencyObject, x)).Where(x => x != null).ToList();
Predicate<Binding> condition = binding => binding != null && binding.Path.Path == propertyName && !sources.Contains(dependencyObject);
foreach (var bindingBase in bindings)
{
if (bindingBase is Binding)
{
if (condition(bindingBase as Binding))
sources.Add(dependencyObject);
}
else if (bindingBase is MultiBinding)
{
if (((MultiBinding)bindingBase).Bindings.Any(bindingBase2 => condition(bindingBase2 as Binding)))
{
sources.Add(dependencyObject);
}
}
else if (bindingBase is PriorityBinding)
{
if (((PriorityBinding)bindingBase).Bindings.Any(bindingBase2 => condition(bindingBase2 as Binding)))
{
sources.Add(dependencyObject);
}
}
}
var children = LogicalTreeHelper.GetChildren(dependencyObject).OfType<DependencyObject>().ToList();
if (children.Count == 0)
return;
foreach(var child in children)
{
GetDependencyObjectsWithBindingToPropertyRecursive(propertyName, child, sources);
}
}
}

Related

WPF ListView with large collection hangs GUI

++++++ Link to example project ++++++
I have a file that can contain thousands of lines of logged messages. I am parsing this file and adding each line (as a log event) to a collection. This collection should then be shown in a ListView.
As below:
<ListView
Grid.Row="0"
Margin="5"
ItemsSource="{Binding SelectedSerilogFileLog.LogEvents}"
ScrollViewer.CanContentScroll="False"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
SelectedItem="{Binding SelectedLogEvent}"
SelectionMode="Single">
The parsing of the file (this one contains 2500+ log events) and adding to the collection takes around 100ms. Then when the bound collection is updated with the ReplaceContent method (this suppresses the collectionchanged event firing on every item added) the GUI hangs, but I cannot see why or what can be causing this.
MainWindow.cs
...
/// <summary>
///
/// </summary>
public SerilogFileLog SelectedSerilogFileLog
{
get => selectedSerilogFileLog; set
{
if (selectedSerilogFileLog != null)
{
SelectedSerilogFileLog.OnSerilogParserFinished -= OnSerilogParserFinished;
SelectedSerilogFileLog.OnSerilogParserProgressChanged -= OnSerilogParserProgressChanged;
}
selectedSerilogFileLog = value;
if (selectedSerilogFileLog != null)
{
ParserProgress = 0;
SelectedSerilogFileLog.OnSerilogParserFinished += OnSerilogParserFinished;
SelectedSerilogFileLog.OnSerilogParserProgressChanged += OnSerilogParserProgressChanged;
sw.Start();
SelectedSerilogFileLog.Parse();
}
NotifyPropertyChanged(nameof(SelectedSerilogFileLog));
}
}
...
private void Button_Click(object sender, RoutedEventArgs e)
{
SelectedSerilogFileLog = null;
SelectedSerilogFileLog = new SerilogFileLog() { FilePath = "Application20210216.log" };
}
The parsing and loading of the items occurs in a separate Task.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace LargeListViewTest.Classes
{
public class SerilogFileLog : INotifyPropertyChanged
{
private LogEvent lastLogEvent;
private ObservableCollectionEx<LogEvent> logEvents;
private string name;
private string description;
private string filePath;
private Regex patternMatching;
private string matchExpression = #"^(?<DateTime>[^|]+)\| (?<Level>[^|]+) \| (?<MachineName>[^|]+) \| (?<Source>[^|]+) \| (?<Message>[^$]*)$";
public delegate void SerilogParserProgressHandler(int Percentage);
public delegate void SerilogParserFinishedHandler();
/// <summary>
///
/// </summary>
public event SerilogParserProgressHandler OnSerilogParserProgressChanged;
/// <summary>
///
/// </summary>
public event SerilogParserFinishedHandler OnSerilogParserFinished;
/// <summary>
/// Gets or sets the LogEvents.
/// </summary>
public ObservableCollectionEx<LogEvent> LogEvents { get => logEvents; private set { logEvents = value; NotifyPropertyChanged(nameof(LogEvents)); } }
/// <summary>
/// Gets or sets the Name.
/// </summary>
public string Name { get => name; private set { name = value; NotifyPropertyChanged(nameof(Name)); } }
/// <summary>
/// Gets or sets the Description.
/// </summary>
public string Description { get => description; private set { description = value; NotifyPropertyChanged(nameof(Description)); } }
/// <summary>
/// Gets or sets the FilePath.
/// </summary>
public string FilePath
{
get => filePath;
set
{
filePath = value;
Name = Path.GetFileNameWithoutExtension(value);
Description = FilePath;
}
}
/// <summary>
///
/// </summary>
public SerilogFileLog()
{
LogEvents = new ObservableCollectionEx<LogEvent>();
patternMatching = new Regex(matchExpression, RegexOptions.Singleline | RegexOptions.Compiled);
}
/// <summary>
///
/// </summary>
public void Parse()
{
Task task = Task.Factory.StartNew(() => { InternalParse(); });
}
/// <summary>
///
/// </summary>
private void InternalParse()
{
OnSerilogParserProgressChanged?.Invoke(0);
try
{
if (!string.IsNullOrWhiteSpace(FilePath))
{
Console.WriteLine("Starting parse for {0}", FilePath);
long currentLength = 0;
FileInfo fi = new FileInfo(FilePath);
if (fi.Exists)
{
Console.WriteLine("Parsing Serilog file: {0}.", FilePath);
fi.Refresh();
List<LogEvent> parsedLogEvents = new List<LogEvent>();
StringBuilder sb = new StringBuilder();
using (FileStream fileStream = fi.Open(FileMode.Open, FileAccess.Read, FileShare.Write))
using (var streamReader = new StreamReader(fileStream))
{
while (streamReader.Peek() != -1)
{
sb.Append(streamReader.ReadLine());
LogEvent newLogEvent = ParseLogEvent(sb.ToString());
if (newLogEvent != null)
{
parsedLogEvents.Add(newLogEvent);
lastLogEvent = newLogEvent;
}
OnSerilogParserProgressChanged?.Invoke((int)(currentLength * 100 / fi.Length));
currentLength = currentLength + sb.ToString().Length;
sb.Clear();
}
}
LogEvents.ReplaceContent(parsedLogEvents);
}
Console.WriteLine("Finished parsing Serilog {0}.", FilePath);
}
}
catch (Exception ex)
{
Console.WriteLine("Error parsing Serilog." + ex.Message);
}
OnSerilogParserProgressChanged?.Invoke(100);
SerilogParserFinishedHandler onSerilogParserFinished = OnSerilogParserFinished;
if (onSerilogParserFinished == null)
return;
OnSerilogParserFinished();
}
/// <summary>
///
/// </summary>
/// <param name="mes"></param>
/// <returns></returns>
private LogEvent ParseLogEvent(string mes)
{
LogEvent logEvent = new LogEvent();
Match matcher = patternMatching.Match(mes);
try
{
if (matcher.Success)
{
logEvent.Message = matcher.Groups["Message"].Value;
DateTime dt;
if (!DateTime.TryParse(matcher.Groups["DateTime"].Value, out dt))
{
Console.WriteLine("Failed to parse date {Value}", matcher.Groups["DateTime"].Value);
}
logEvent.DateTime = dt;
logEvent.Level = matcher.Groups["Level"].Value;
logEvent.MachineName = matcher.Groups["MachineName"].Value;
logEvent.Source = matcher.Groups["Source"].Value;
}
else
{
if ((string.IsNullOrEmpty(mes) || (!Char.IsDigit(mes[0])) || !Char.IsDigit(mes[1])) && lastLogEvent != null)
{
// seems to be a continuation of the previous line, add it to the last event.
lastLogEvent.Message += Environment.NewLine;
lastLogEvent.Message += mes;
logEvent = null;
}
else
{
Console.WriteLine("Message parsing failed.");
}
if (logEvent != null)
logEvent.Message = mes;
}
}
catch (Exception ex)
{
Console.WriteLine("ParseLogEvent exception." + ex.Message);
}
return logEvent;
}
#region INotify
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string p) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(p));
#endregion
}
}
I have an ObservableCollectionEx class that extends the default ObservableCollection, this class suppresses the collection changed event until all the items have been added/replaced.
/// <summary>
/// Adds the supplied items to the collection and raises a single <see cref="CollectionChanged"/> event
/// when the operation is complete.
/// </summary>
/// <param name="items">The items to add.</param>
public void AddRange(IEnumerable<T> items, bool notifyAfter = true)
{
if (null == items)
{
throw new ArgumentNullException("items");
}
if (items.Any())
{
try
{
SuppressChangeNotification();
CheckReentrancy();
foreach (var item in items)
{
Add(item);
}
}
finally
{
if (notifyAfter)
FireChangeNotification();
suppressOnCollectionChanged = false;
}
}
}
/// <summary>
/// Replaces the content of the collection with the supplied items and raises a single <see cref="CollectionChanged"/> event
/// when the operation is complete.
/// </summary>
/// <param name="items">The items to replace the current content.</param>
public void ReplaceContent(IEnumerable<T> items)
{
SuppressChangeNotification();
ClearItems();
AddRange(items);
}
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
if (!suppressOnCollectionChanged)
{
#if NoCrossThreadSupport
base.OnCollectionChanged(e);
#else
using (BlockReentrancy())
{
NotifyCollectionChangedEventHandler eventHandler = CollectionChanged;
if (eventHandler == null)
return;
Delegate[] delegates = eventHandler.GetInvocationList();
// Walk the invocation list
foreach (NotifyCollectionChangedEventHandler handler in delegates)
{
DispatcherObject dispatcherObject = handler.Target as DispatcherObject;
// If the subscriber is a DispatcherObject and different thread
if (dispatcherObject != null && !dispatcherObject.CheckAccess())
{
// Invoke handler in the target dispatcher's thread
dispatcherObject.Dispatcher.Invoke(DispatcherPriority.DataBind, handler, this, e);
}
else // Execute handler as is
handler(this, e);
}
}
#endif
}
}
I have tried using a List but I got the same behaviour.
Any ideas?

How can I get a CheckEdit in a NavBarGroup

We need to place a check box (and caption for it) in the header of a NavBarGroup. Is there a way to do this?
We created a NavBarGroupChecked class (NavBarGroupChecked.cs) that inherits from NavBarGroup and can just be dropped in to replace it. It adds a RepositoryItemCheckEdit member that tracks the checkbox and implements custom draw. It has a Checked property that tells you if it is checked and an event that will be called when the Checked status changes. That's pretty much it. Just drops in and works.
Code is below and also downloadable here.
// built from http://www.devexpress.com/example=E2061
using System;
using System.ComponentModel;
using System.Drawing;
using System.Reflection;
using System.Windows.Forms;
using DevExpress.XtraEditors.Drawing;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraEditors.ViewInfo;
using DevExpress.XtraNavBar;
using DevExpress.XtraNavBar.ViewInfo;
namespace AutoTagCore.net.windward.controls
{
/// <summary>
/// A NavBarGroup that has a check box (with caption) in its header.
/// </summary>
public class NavBarGroupChecked : NavBarGroup
{
/// <summary>
/// Occurs when the Checked property value has been changed.
/// </summary>
public event EventHandler CheckedChanged;
private const int CHECK_BOX_WIDTH = 15;
private bool isLocked;
private RepositoryItemCheckEdit _GroupEdit;
private NavBarControl _NavBarControl;
private Rectangle hotRectangle;
/// <summary>
/// Initializes a new instance of the <see cref="T:DevExpress.XtraNavBar.NavBarGroup"/> class, with the specified caption.
/// </summary>
/// <param name="caption">A string representing the NavBar group's caption.</param>
public NavBarGroupChecked(string caption)
: base(caption)
{
ctor();
}
private void ctor()
{
GroupEdit = new RepositoryItemCheckEdit { GlyphAlignment = DevExpress.Utils.HorzAlignment.Far };
GroupEdit.Appearance.Options.UseTextOptions = true;
GroupEdit.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far;
GroupEdit.GlyphAlignment = DevExpress.Utils.HorzAlignment.Far;
ItemChanged += NavBarGroupChecked_ItemChanged;
}
private void NavBarGroupChecked_ItemChanged(object sender, System.EventArgs e)
{
if (NavBar != NavBarControl)
NavBarControl = NavBar;
}
/// <summary>
/// Creates an instance of the <see cref="T:DevExpress.XtraNavBar.NavBarGroup"/> class.
/// </summary>
public NavBarGroupChecked()
{
ctor();
}
/// <summary>
/// The NavBarControl that owns this. This must be set to work.
/// </summary>
private NavBarControl NavBarControl
{
get { return _NavBarControl; }
set { UnsubscribeEvents(value); _NavBarControl = value; SubscribeEvents(value); }
}
private void SubscribeEvents(NavBarControl navBarControl)
{
if (navBarControl == null)
return;
NavBarControl.CustomDrawGroupCaption += NavBarControl_CustomDrawGroupCaption;
NavBarControl.MouseClick += NavBarControl_MouseClick;
}
private void UnsubscribeEvents(NavBarControl navBarControl)
{
if (navBarControl != null)
return;
NavBarControl.CustomDrawGroupCaption -= NavBarControl_CustomDrawGroupCaption;
NavBarControl.MouseClick -= NavBarControl_MouseClick;
}
/// <summary>
/// true if the box is checked.
/// </summary>
public bool Checked { get; set; }
/// <summary>
/// The indent of the check box for the end of the header.
/// </summary>
public int CheckIndent { get; set; }
///<summary>
/// The check box displayed in the header.
///</summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public RepositoryItemCheckEdit GroupEdit
{
get { return _GroupEdit; }
set { _GroupEdit = value; }
}
private Rectangle GetCheckBoxBounds(Rectangle fixedCaptionBounds)
{
return new Rectangle(fixedCaptionBounds.Right - CHECK_BOX_WIDTH - CheckIndent, fixedCaptionBounds.Top, CHECK_BOX_WIDTH, fixedCaptionBounds.Height);
}
private bool IsCustomDrawNeeded(NavBarGroup group)
{
return GroupEdit != null && NavBarControl != null && !isLocked && group == this;
}
private void NavBarControl_CustomDrawGroupCaption(object sender, CustomDrawNavBarElementEventArgs e)
{
NavGroupInfoArgs infoArgs = (NavGroupInfoArgs) e.ObjectInfo;
if (!IsCustomDrawNeeded(infoArgs.Group))
return;
try
{
isLocked = true;
BaseNavGroupPainter painter = NavBarControl.View.CreateGroupPainter(NavBarControl);
Rectangle checkBoxBounds = GetCheckBoxBounds(infoArgs.CaptionBounds);
painter.DrawObject(infoArgs);
DrawCheckBox(e.Graphics, checkBoxBounds);
e.Handled = true;
}
finally
{
isLocked = false;
}
}
private void DrawCheckBox(Graphics g, Rectangle r)
{
BaseEditPainter painter = GroupEdit.CreatePainter();
BaseEditViewInfo info = GroupEdit.CreateViewInfo();
info.EditValue = Checked;
SizeF textBounds = info.Appearance.CalcTextSize(g, GroupEdit.Caption, 500);
int totalWidth = (int)textBounds.Width + r.Width + 10;
info.Bounds = new Rectangle(r.Right - totalWidth, r.Y, totalWidth, r.Height);
info.CalcViewInfo(g);
ControlGraphicsInfoArgs args = new ControlGraphicsInfoArgs(info, new DevExpress.Utils.Drawing.GraphicsCache(g), r);
painter.Draw(args);
args.Cache.Dispose();
}
private static NavBarViewInfo GetNavBarView(NavBarControl NavBar)
{
PropertyInfo pi = typeof(NavBarControl).GetProperty("ViewInfo", BindingFlags.Instance | BindingFlags.NonPublic);
return pi.GetValue(NavBar, null) as NavBarViewInfo;
}
private bool IsCheckBox(Point p)
{
NavBarHitInfo hi = NavBarControl.CalcHitInfo(p);
if (hi.Group == null || hi.Group != this)
return false;
NavBarViewInfo vi = GetNavBarView(NavBarControl);
vi.Calc(NavBarControl.ClientRectangle);
NavGroupInfoArgs groupInfo = vi.GetGroupInfo(hi.Group);
Rectangle checkBounds = GetCheckBoxBounds(groupInfo.CaptionBounds);
hotRectangle = checkBounds;
return checkBounds.Contains(p);
}
private void NavBarControl_MouseClick(object sender, MouseEventArgs e)
{
if (!IsCheckBox(e.Location))
return;
Checked = !Checked;
NavBarControl.Invalidate(hotRectangle);
if (CheckedChanged != null)
CheckedChanged(sender, e);
}
}
}
I had some issues with the way that solution worked and made some minor tweaks. See below.
A sample on how to use this is;
private void Form1_Load(object sender, EventArgs e)
{
var item = navBarControl1.Groups.Add(new NavBarGroupChecked("NavBarGroupCheckbox", navBarControl1)) as NavBarGroupChecked;
item.Hint = "my hint";
item.CheckedChanged += checkchanged;
}
private void checkchanged(object sender, EventArgs e)
{
MessageBox.Show("It Changed");
}
This is the solution:
// built from http://www.devexpress.com/example=E2061
using System;
using System.ComponentModel;
using System.Drawing;
using System.Reflection;
using System.Windows.Forms;
using DevExpress.XtraEditors.Drawing;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraEditors.ViewInfo;
using DevExpress.XtraNavBar;
using DevExpress.XtraNavBar.ViewInfo;
namespace NavBarCheckTest
{
/// <summary>
/// A NavBarGroup that has a check box (with caption) in its header.
/// </summary>
public class NavBarGroupChecked : NavBarGroup
{
/// <summary>
/// Occurs when the Checked property value has been changed.
/// </summary>
public event EventHandler CheckedChanged;
private const int CHECK_BOX_WIDTH = 15;
private bool isLocked;
private RepositoryItemCheckEdit _GroupEdit;
private NavBarControl _NavBarControl;
private Rectangle hotRectangle;
/// <summary>
/// Initializes a new instance of the <see cref="T:DevExpress.XtraNavBar.NavBarGroup"/> class, with the specified caption.
/// </summary>
/// <param name="caption">A string representing the NavBar group's caption.</param>
public NavBarGroupChecked(string caption, NavBarControl parent = null)
: base(caption)
{
ctor(parent);
}
private void ctor(NavBarControl parent = null)
{
GroupEdit = new RepositoryItemCheckEdit { GlyphAlignment = DevExpress.Utils.HorzAlignment.Far };
GroupEdit.Caption = string.Empty;
GroupEdit.Appearance.Options.UseTextOptions = true;
GroupEdit.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far;
GroupEdit.GlyphAlignment = DevExpress.Utils.HorzAlignment.Far;
ItemChanged += NavBarGroupChecked_ItemChanged;
if (parent != null)
NavBarControl = parent;
}
private void NavBarGroupChecked_ItemChanged(object sender, System.EventArgs e)
{
if (NavBar != NavBarControl)
NavBarControl = NavBar;
}
/// <summary>
/// Creates an instance of the <see cref="T:DevExpress.XtraNavBar.NavBarGroup"/> class.
/// </summary>
public NavBarGroupChecked(NavBarControl parent = null)
{
ctor(parent);
}
/// <summary>
/// The NavBarControl that owns this. This must be set to work.
/// </summary>
private NavBarControl NavBarControl
{
get { return _NavBarControl; }
set { UnsubscribeEvents(value); _NavBarControl = value; SubscribeEvents(value); }
}
private void SubscribeEvents(NavBarControl navBarControl)
{
if (navBarControl == null)
return;
NavBarControl.CustomDrawGroupCaption += NavBarControl_CustomDrawGroupCaption;
NavBarControl.MouseClick += NavBarControl_MouseClick;
}
private void UnsubscribeEvents(NavBarControl navBarControl)
{
if (navBarControl != null)
return;
NavBarControl.CustomDrawGroupCaption -= NavBarControl_CustomDrawGroupCaption;
NavBarControl.MouseClick -= NavBarControl_MouseClick;
}
/// <summary>
/// true if the box is checked.
/// </summary>
public bool Checked { get; set; }
/// <summary>
/// The indent of the check box for the end of the header.
/// </summary>
public int CheckIndent { get; set; }
///<summary>
/// The check box displayed in the header.
///</summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public RepositoryItemCheckEdit GroupEdit
{
get { return _GroupEdit; }
set { _GroupEdit = value; }
}
private int GetCheckBoxWidth()
{
return CheckIndent * 2 + 10;
}
//private Rectangle GetCaptionBounds(Rectangle originalCaptionBounds)
//{
// return new Rectangle(originalCaptionBounds.Location, new Size(originalCaptionBounds.Width - GetCheckBoxWidth(), originalCaptionBounds.Height));
//}
private Rectangle GetCheckBoxBounds(Rectangle fixedCaptionBounds)
{
return new Rectangle(fixedCaptionBounds.Right - CHECK_BOX_WIDTH - CheckIndent, fixedCaptionBounds.Top, CHECK_BOX_WIDTH, fixedCaptionBounds.Height);
//return new Rectangle(fixedCaptionBounds.Right, fixedCaptionBounds.Top, GetCheckBoxWidth(), fixedCaptionBounds.Height); ;
}
private bool IsCustomDrawNeeded(NavBarGroup group)
{
return GroupEdit != null && NavBarControl != null && !isLocked && group == this;
}
private void NavBarControl_CustomDrawGroupCaption(object sender, CustomDrawNavBarElementEventArgs e)
{
NavGroupInfoArgs infoArgs = (NavGroupInfoArgs) e.ObjectInfo;
if (!IsCustomDrawNeeded(infoArgs.Group))
return;
try
{
isLocked = true;
BaseNavGroupPainter painter = NavBarControl.View.CreateGroupPainter(NavBarControl);
Rectangle originalCaptionBounds = new Rectangle(infoArgs.CaptionClientBounds.X, infoArgs.CaptionClientBounds.Y, infoArgs.CaptionClientBounds.Width - infoArgs.ButtonBounds.Width, infoArgs.CaptionClientBounds.Height);
Rectangle checkBoxBounds = GetCheckBoxBounds(originalCaptionBounds);
painter.DrawObject(infoArgs);
DrawCheckBox(e.Graphics, checkBoxBounds);
e.Handled = true;
}
finally
{
isLocked = false;
}
}
private void DrawCheckBox(Graphics g, Rectangle r)
{
BaseEditPainter painter = GroupEdit.CreatePainter();
BaseEditViewInfo info = GroupEdit.CreateViewInfo();
info.EditValue = Checked;
SizeF textBounds = info.Appearance.CalcTextSize(g, GroupEdit.Caption, 500);
int totalWidth = (int)textBounds.Width + r.Width + 10;
info.Bounds = new Rectangle(r.Right - totalWidth, r.Y, totalWidth, r.Height);
info.CalcViewInfo(g);
ControlGraphicsInfoArgs args = new ControlGraphicsInfoArgs(info, new DevExpress.Utils.Drawing.GraphicsCache(g), r);
painter.Draw(args);
args.Cache.Dispose();
}
private static NavBarViewInfo GetNavBarView(NavBarControl NavBar)
{
PropertyInfo pi = typeof(NavBarControl).GetProperty("ViewInfo", BindingFlags.Instance | BindingFlags.NonPublic);
return pi.GetValue(NavBar, null) as NavBarViewInfo;
}
private bool IsCheckBox(Point p)
{
NavBarHitInfo hi = NavBarControl.CalcHitInfo(p);
if (hi.Group == null || hi.Group != this)
return false;
NavBarViewInfo vi = GetNavBarView(NavBarControl);
vi.Calc(NavBarControl.ClientRectangle);
NavGroupInfoArgs groupInfo = vi.GetGroupInfo(hi.Group);
Rectangle originalCaptionBounds = new Rectangle(groupInfo.CaptionClientBounds.X, groupInfo.CaptionClientBounds.Y, groupInfo.CaptionClientBounds.Width - groupInfo.ButtonBounds.Width, groupInfo.CaptionClientBounds.Height);
Rectangle checkBounds = GetCheckBoxBounds(originalCaptionBounds);
hotRectangle = checkBounds;
return checkBounds.Contains(p);
}
private void NavBarControl_MouseClick(object sender, MouseEventArgs e)
{
if (!IsCheckBox(e.Location))
return;
Checked = !Checked;
NavBarControl.Invalidate(hotRectangle);
if (CheckedChanged != null)
CheckedChanged(sender, e);
}
}
}

How to get WPF DataGridCell visual horizontal (X-axis) position?

I need to get the position of a WPF DataGridCell, obtained in a DataGrid cell changed event, but only can get the vertical (Y-axis).
The horizontal remains the same, despite a different column is pointed.
Here is the almost working code.
Test by clicking on different cells.
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
List<Person> Persons = new List<Person>();
public MainWindow()
{
InitializeComponent();
Persons.Add(new Person { Id = 1, Name = "John", City = "London" });
Persons.Add(new Person { Id = 2, Name = "Charles", City = "Rome" });
Persons.Add(new Person { Id = 3, Name = "Paul", City = "Chicago" });
this.EditingDataGrid.ItemsSource = Persons;
this.EditingDataGrid.CurrentCellChanged += new EventHandler<EventArgs>(EditingDataGrid_CurrentCellChanged);
}
void EditingDataGrid_CurrentCellChanged(object sender, EventArgs e)
{
DataGridCell Cell = GetCurrentCell(this.EditingDataGrid);
var Position = Cell.PointToScreen(new Point(0, 0));
// WHY X NEVER CHANGES??!!
MessageBox.Show("X=" + Position.X.ToString() + ", Y=" + Position.Y.ToString(), "Position");
}
/// <summary>
/// Returns, for this supplied Source Data-Grid, the current Data-Grid-Cell.
/// May return null if no associated Cell is found.
/// </summary>
public static DataGridCell GetCurrentCell(DataGrid SourceDataGrid)
{
if (SourceDataGrid.CurrentCell == null)
return null;
var RowContainer = SourceDataGrid.ItemContainerGenerator.ContainerFromItem(SourceDataGrid.CurrentCell.Item);
if (RowContainer == null)
return null;
var RowPresenter = GetVisualChild<System.Windows.Controls.Primitives.DataGridCellsPresenter>(RowContainer);
if (RowPresenter == null)
return null;
var Container = RowPresenter.ItemContainerGenerator.ContainerFromItem(SourceDataGrid.CurrentCell.Item);
var Cell = Container as DataGridCell;
// Try to get the cell if null, because maybe the cell is virtualized
if (Cell == null)
{
SourceDataGrid.ScrollIntoView(RowContainer, SourceDataGrid.CurrentCell.Column);
Container = RowPresenter.ItemContainerGenerator.ContainerFromItem(SourceDataGrid.CurrentCell.Item);
Cell = Container as DataGridCell;
}
return Cell;
}
/// <summary>
/// Returns the nearest child having the specified TRet type for the supplied Target.
/// </summary>
public static TRet GetVisualChild<TRet>(DependencyObject Target) where TRet : DependencyObject
{
if (Target == null)
return null;
for (int ChildIndex = 0; ChildIndex < VisualTreeHelper.GetChildrenCount(Target); ChildIndex++)
{
var Child = VisualTreeHelper.GetChild(Target, ChildIndex);
if (Child != null && Child is TRet)
return (TRet)Child;
else
{
TRet childOfChild = GetVisualChild<TRet>(Child);
if (childOfChild != null)
return childOfChild;
}
}
return null;
}
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
}
The DataGrid is just defined by...
<DataGrid x:Name="EditingDataGrid"/>
Maybe exists there an alternative to get that DataGridCell position?
You can get the DataGridCell from CurrentCell like this
void EditingDataGrid_CurrentCellChanged(object sender, EventArgs e)
{
DataGridCell Cell = GetDataGridCell(EditingDataGrid.CurrentCell);
var Position = Cell.PointToScreen(new Point(0, 0));
MessageBox.Show("X=" + Position.X.ToString() + ", Y=" + Position.Y.ToString(), "Position");
}
public static DataGridCell GetDataGridCell(DataGridCellInfo cellInfo)
{
if (cellInfo.IsValid == false)
{
return null;
}
var cellContent = cellInfo.Column.GetCellContent(cellInfo.Item);
if (cellContent == null)
{
return null;
}
return cellContent.Parent as DataGridCell;
}
You could also create an extension method on the DataGrid to do this
DataGridExtensions.cs
public static class DataGridExtensions
{
public static DataGridCell GetCurrentDataGridCell(this DataGrid dataGrid)
{
DataGridCellInfo cellInfo = dataGrid.CurrentCell;
if (cellInfo.IsValid == false)
{
return null;
}
var cellContent = cellInfo.Column.GetCellContent(cellInfo.Item);
if (cellContent == null)
{
return null;
}
return cellContent.Parent as DataGridCell;
}
}
Which you can use like this everytime you want to get the current DataGridCell
DataGridCell Cell = EditingDataGrid.GetCurrentDataGridCell();
I guess what's going on is that your grid's default selection mode is full row, the code you're using to get the DataGridCell is getting the first selected cell which holds the "Id" column value.
What you can try to do is changing the grid's selection mode to "Cell" and this trigger the message box with correct coordinates.
<DataGrid x:Name="EditingDataGrid" SelectionUnit="Cell"/>
Also I've changed your code a bit, see if it would work for you:
void EditingDataGrid_CurrentCellChanged(object sender, EventArgs e)
{
// this will iterate through all selected cell of the datagrid
foreach (DataGridCellInfo cellInfo in this.EditingDataGrid.SelectedCells)
{
DataGridCell Cell = GetCurrentCell(this.EditingDataGrid, cellInfo);
if (Cell != null)
{
var Position = Cell.PointToScreen(new Point(0, 0));
MessageBox.Show("X=" + Position.X.ToString() +
", Y=" + Position.Y.ToString() +
" Content = " + ((TextBlock)Cell.Content).Text.ToString(), "Position");
}
}
}
/// <summary>
/// Returns, for this supplied Source Data-Grid, the current Data-Grid-Cell.
/// May return null if no associated Cell is found.
/// </summary>
public static DataGridCell GetCurrentCell(DataGrid grid, DataGridCellInfo cellInfo)
{
DataGridCell result = null;
DataGridRow row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromItem(cellInfo.Item);
if (row != null)
{
int columnIndex = grid.Columns.IndexOf(cellInfo.Column);
if (columnIndex > -1)
{
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row);
result = presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex) as DataGridCell;
}
}
return result;
}
/// <summary>
/// Returns the nearest child having the specified TRet type for the supplied Target.
/// </summary>
static T GetVisualChild<T>(Visual parent) where T : Visual
{
T child = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
child = v as T;
if (child == null)
{
child = GetVisualChild<T>(v);
}
if (child != null)
{
break;
}
}
return child;
}
hope this helps, regards

Databind a read only dependency property to ViewModel in Xaml

I'm trying to databind a Button's IsMouseOver read-only dependency property to a boolean read/write property in my view model.
Basically I need the Button's IsMouseOver property value to be read to a view model's property.
<Button IsMouseOver="{Binding Path=IsMouseOverProperty, Mode=OneWayToSource}" />
I'm getting a compile error: 'IsMouseOver' property is read-only and cannot be set from markup. What am I doing wrong?
No mistake. This is a limitation of WPF - a read-only property cannot be bound OneWayToSource unless the source is also a DependencyProperty.
An alternative is an attached behavior.
As many people have mentioned, this is a bug in WPF and the best way is to do it is attached property like Tim/Kent suggested. Here is the attached property I use in my project. I intentionally do it this way for readability, unit testability, and sticking to MVVM without codebehind on the view to handle the events manually everywhere.
public interface IMouseOverListener
{
void SetIsMouseOver(bool value);
}
public static class ControlExtensions
{
public static readonly DependencyProperty MouseOverListenerProperty =
DependencyProperty.RegisterAttached("MouseOverListener", typeof (IMouseOverListener), typeof (ControlExtensions), new PropertyMetadata(OnMouseOverListenerChanged));
private static void OnMouseOverListenerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var element = ((UIElement)d);
if(e.OldValue != null)
{
element.MouseEnter -= ElementOnMouseEnter;
element.MouseLeave -= ElementOnMouseLeave;
}
if(e.NewValue != null)
{
element.MouseEnter += ElementOnMouseEnter;
element.MouseLeave += ElementOnMouseLeave;
}
}
public static void SetMouseOverListener(UIElement element, IMouseOverListener value)
{
element.SetValue(MouseOverListenerProperty, value);
}
public static IMouseOverListener GetMouseOverListener(UIElement element)
{
return (IMouseOverListener) element.GetValue(MouseOverListenerProperty);
}
private static void ElementOnMouseLeave(object sender, MouseEventArgs mouseEventArgs)
{
var element = ((UIElement)sender);
var listener = GetMouseOverListener(element);
if(listener != null)
listener.SetIsMouseOver(false);
}
private static void ElementOnMouseEnter(object sender, MouseEventArgs mouseEventArgs)
{
var element = ((UIElement)sender);
var listener = GetMouseOverListener(element);
if (listener != null)
listener.SetIsMouseOver(true);
}
}
Here's a rough draft of what i resorted to while seeking a general solution to this problem. It employs a css-style formatting to specify Dependency-Properties to be bound to model properties (models gotten from the DataContext); this also means it will work only on FrameworkElements.
I haven't thoroughly tested it, but the happy path works just fine for the few test cases i ran.
public class BindingInfo
{
internal string sourceString = null;
public DependencyProperty source { get; internal set; }
public string targetProperty { get; private set; }
public bool isResolved => source != null;
public BindingInfo(string source, string target)
{
this.sourceString = source;
this.targetProperty = target;
validate();
}
private void validate()
{
//verify that targetProperty is a valid c# property access path
if (!targetProperty.Split('.')
.All(p => Identifier.IsMatch(p)))
throw new Exception("Invalid target property - " + targetProperty);
//verify that sourceString is a [Class].[DependencyProperty] formatted string.
if (!sourceString.Split('.')
.All(p => Identifier.IsMatch(p)))
throw new Exception("Invalid source property - " + sourceString);
}
private static readonly Regex Identifier = new Regex(#"[_a-z][_\w]*$", RegexOptions.IgnoreCase);
}
[TypeConverter(typeof(BindingInfoConverter))]
public class BindingInfoGroup
{
private List<BindingInfo> _infoList = new List<BindingInfo>();
public IEnumerable<BindingInfo> InfoList
{
get { return _infoList.ToArray(); }
set
{
_infoList.Clear();
if (value != null) _infoList.AddRange(value);
}
}
}
public class BindingInfoConverter: TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string)) return true;
return base.CanConvertFrom(context, sourceType);
}
// Override CanConvertTo to return true for Complex-to-String conversions.
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(string)) return true;
return base.CanConvertTo(context, destinationType);
}
// Override ConvertFrom to convert from a string to an instance of Complex.
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
string text = value as string;
return new BindingInfoGroup
{
InfoList = text.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
.Select(binfo =>
{
var parts = binfo.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length != 2) throw new Exception("invalid binding info - " + binfo);
return new BindingInfo(parts[0].Trim(), parts[1].Trim());
})
};
}
// Override ConvertTo to convert from an instance of Complex to string.
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture,
object value, Type destinationType)
{
var bgroup = value as BindingInfoGroup;
return bgroup.InfoList
.Select(bi => $"{bi.sourceString}:{bi.targetProperty};")
.Aggregate((n, p) => n += $"{p} ")
.Trim();
}
public override bool GetStandardValuesSupported(ITypeDescriptorContext context) => false;
}
public class Bindings
{
#region Fields
private static ConcurrentDictionary<DependencyProperty, PropertyChangeHandler> _Properties =
new ConcurrentDictionary<DependencyProperty, PropertyChangeHandler>();
#endregion
#region OnewayBindings
public static readonly DependencyProperty OnewayBindingsProperty =
DependencyProperty.RegisterAttached("OnewayBindings", typeof(BindingInfoGroup), typeof(Bindings), new FrameworkPropertyMetadata
{
DefaultValue = null,
PropertyChangedCallback = (x, y) =>
{
var fwe = x as FrameworkElement;
if (fwe == null) return;
//resolve the bindings
resolve(fwe);
//add change delegates
(GetOnewayBindings(fwe)?.InfoList ?? new BindingInfo[0])
.Where(bi => bi.isResolved)
.ToList()
.ForEach(bi =>
{
var descriptor = DependencyPropertyDescriptor.FromProperty(bi.source, fwe.GetType());
PropertyChangeHandler listener = null;
if (_Properties.TryGetValue(bi.source, out listener))
{
descriptor.RemoveValueChanged(fwe, listener.callback); //cus there's no way to check if it had one before...
descriptor.AddValueChanged(fwe, listener.callback);
}
});
}
});
private static void resolve(FrameworkElement element)
{
var bgroup = GetOnewayBindings(element);
bgroup.InfoList
.ToList()
.ForEach(bg =>
{
//source
var sourceParts = bg.sourceString.Split('.');
if (sourceParts.Length == 1)
{
bg.source = element.GetType()
.baseTypes() //<- flattens base types, including current type
.SelectMany(t => t.GetRuntimeFields()
.Where(p => p.IsStatic)
.Where(p => p.FieldType == typeof(DependencyProperty)))
.Select(fi => fi.GetValue(null) as DependencyProperty)
.FirstOrDefault(dp => dp.Name == sourceParts[0])
.ThrowIfNull($"Dependency Property '{sourceParts[0]}' was not found");
}
else
{
//resolve the dependency property [ClassName].[PropertyName]Property - e.g FrameworkElement.DataContextProperty
bg.source = Type.GetType(sourceParts[0])
.GetField(sourceParts[1])
.GetValue(null)
.ThrowIfNull($"Dependency Property '{bg.sourceString}' was not found") as DependencyProperty;
}
_Properties.GetOrAdd(bg.source, ddp => new PropertyChangeHandler { property = ddp }); //incase it wasnt added before.
});
}
public static BindingInfoGroup GetOnewayBindings(FrameworkElement source)
=> source.GetValue(OnewayBindingsProperty) as BindingInfoGroup;
public static void SetOnewayBindings(FrameworkElement source, string value)
=> source.SetValue(OnewayBindingsProperty, value);
#endregion
}
public class PropertyChangeHandler
{
internal DependencyProperty property { get; set; }
public void callback(object obj, EventArgs args)
{
var fwe = obj as FrameworkElement;
var target = fwe.DataContext;
if (fwe == null) return;
if (target == null) return;
var bg = Bindings.GetOnewayBindings(fwe);
if (bg == null) return;
else bg.InfoList
.Where(bi => bi.isResolved)
.Where(bi => bi.source == property)
.ToList()
.ForEach(bi =>
{
//transfer data to the object
var data = fwe.GetValue(property);
KeyValuePair<object, PropertyInfo>? pinfo = resolveProperty(target, bi.targetProperty);
if (pinfo == null) return;
else pinfo.Value.Value.SetValue(pinfo.Value.Key, data);
});
}
private KeyValuePair<object, PropertyInfo>? resolveProperty(object target, string path)
{
try
{
var parts = path.Split('.');
if (parts.Length == 1) return new KeyValuePair<object, PropertyInfo>(target, target.GetType().GetProperty(parts[0]));
else //(parts.Length>1)
return resolveProperty(target.GetType().GetProperty(parts[0]).GetValue(target),
string.Join(".", parts.Skip(1)));
}
catch (Exception e) //too lazy to care :D
{
return null;
}
}
}
And to use the XAML...
<Grid ab:Bindings.OnewayBindings="IsMouseOver:mouseOver;">...</Grid>

How can I implement a commandable ColumnSeries in the WPF Toolkit's Chart Control

I need to be able to specify a command to run when the SelectionChanged event fires. I already know how to implement the ICommandSource interface; what I need to know is how I can just add a command to the column series to handle the SelectionChanged event.
When I inherit from the ColumnBarBaseSeries<...> base class I have to override GetAxes() and UpdateDatePoint() which I am not sure how to implement.
You can use attached behaviours to solve this problem.
Create a SelectionChangedBehaviour that wires a selectionChanged event to the element that you're attaching the behaviour to then you can binding any ICommand to that behaviour.
For more on attached behaviours -
Introduction article by Josh Smith
Overview of the concept
Another good introduction
Hope that helps
Here is some code to add an attached behavior to a ColumnSeries for a SelectionChanged Command.
public static class ColumnSeriesBehavior
{
private static DelegateCommand<object> SelectionChangedCommand;
public static DelegateCommand<object> GetSelectionChangedCommand(ColumnSeries cs)
{
return cs.GetValue(SelectionChangedCommandProperty) as DelegateCommand<object>;
}
public static void SetSelectionChangedCommand(ColumnSeries cs, DelegateCommand<object> value)
{
cs.SetValue(SelectionChangedCommandProperty, value);
}
// Using a DependencyProperty as the backing store for SelectionChangedCommand. This enables animation, styling, binding, etc...
public static readonly DependencyProperty SelectionChangedCommandProperty =
DependencyProperty.RegisterAttached("SelectionChangedCommand", typeof(DelegateCommand<object>), typeof(ColumnSeriesBehavior), new UIPropertyMetadata(null, OnSelectionChangedCommandChanged));
private static void OnSelectionChangedCommandChanged(
DependencyObject depObj, DependencyPropertyChangedEventArgs e)
{
ColumnSeries item = depObj as ColumnSeries;
if (item == null)
{
return;
}
if (e.NewValue is DelegateCommand<object> == false)
{
return;
}
SelectionChangedCommand = e.NewValue as DelegateCommand<object>;
item.SelectionChanged += new System.Windows.Controls.SelectionChangedEventHandler(Column_SelectionChanged);
}
private static void Column_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
if (SelectionChangedCommand != null)
SelectionChangedCommand.Execute(sender);
}
}
And in the XAML to attach the property:
<chartingToolkit:Chart.Series>
<chartingToolkit:ColumnSeries
IsSelectionEnabled="True"
ItemsSource="{Binding YourItemSource}"
IndependentValueBinding="{Binding YourIndValue, Path=YourIndValuePath}"
DependentValueBinding="{Binding YourDepValue, Path=YourDepValuePath}"
>
<chartingToolkit:ColumnSeries.Style>
<Style>
<!-- Attaching the SelectionChangedCommand behavior -->
<Setter Property="local:ColumnSeriesBehavior.SelectionChangedCommand"
Value="{Binding YourDelegateCommand}"/>
</Style>
</chartingToolkit:ColumnSeries.Style>
</chartingToolkit:ColumnSeries>
</chartingToolkit:Chart.Series>
Here is some code that appears to work for me to implement your own CommandColumnSeries, I stole a lot of it from the source for the ColumnSeries Sealed Class:
public class CommandColumnSeries : ColumnBarBaseSeries<ColumnDataPoint>
{
#region "ICommandSource"
[Localizability(LocalizationCategory.NeverLocalize), Category("Action"), Bindable(true)]
public ICommand Command
{
get
{
return (ICommand)base.GetValue(CommandProperty);
}
set
{
base.SetValue(CommandProperty, value);
}
}
[Bindable(true), Category("Action"), Localizability(LocalizationCategory.NeverLocalize)]
public object CommandParameter
{
get
{
return base.GetValue(CommandParameterProperty);
}
set
{
base.SetValue(CommandParameterProperty, value);
}
}
[Category("Action"), Bindable(true)]
public IInputElement CommandTarget
{
get
{
return (IInputElement)base.GetValue(CommandTargetProperty);
}
set
{
base.SetValue(CommandTargetProperty, value);
}
}
public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register("CommandParameter", typeof(object), typeof(CommandColumnSeries), new FrameworkPropertyMetadata(null));
public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(CommandColumnSeries), new FrameworkPropertyMetadata(null));
public static readonly DependencyProperty CommandTargetProperty = DependencyProperty.Register("CommandTarget", typeof(IInputElement), typeof(CommandColumnSeries), new FrameworkPropertyMetadata(null));
#endregion
#region public IRangeAxis DependentRangeAxis
/// <summary>
/// Gets or sets the dependent range axis.
/// </summary>
public IRangeAxis DependentRangeAxis
{
get { return GetValue(DependentRangeAxisProperty) as IRangeAxis; }
set { SetValue(DependentRangeAxisProperty, value); }
}
/// <summary>
/// Identifies the DependentRangeAxis dependency property.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes", Justification = "This member is necessary because the base classes need to share this dependency property.")]
public static readonly DependencyProperty DependentRangeAxisProperty =
DependencyProperty.Register(
"DependentRangeAxis",
typeof(IRangeAxis),
typeof(ColumnSeries),
new PropertyMetadata(null, OnDependentRangeAxisPropertyChanged));
/// <summary>
/// DependentRangeAxisProperty property changed handler.
/// </summary>
/// <param name="d">ColumnBarBaseSeries that changed its DependentRangeAxis.</param>
/// <param name="e">Event arguments.</param>
private static void OnDependentRangeAxisPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
CommandColumnSeries source = (CommandColumnSeries)d;
IRangeAxis newValue = (IRangeAxis)e.NewValue;
source.OnDependentRangeAxisPropertyChanged(newValue);
}
/// <summary>
/// DependentRangeAxisProperty property changed handler.
/// </summary>
/// <param name="newValue">New value.</param>
private void OnDependentRangeAxisPropertyChanged(IRangeAxis newValue)
{
this.InternalDependentAxis = (IAxis)newValue;
}
#endregion public IRangeAxis DependentRangeAxis
#region public IAxis IndependentAxis
/// <summary>
/// Gets or sets the independent category axis.
/// </summary>
public IAxis IndependentAxis
{
get { return GetValue(IndependentAxisProperty) as IAxis; }
set { SetValue(IndependentAxisProperty, value); }
}
/// <summary>
/// Identifies the IndependentAxis dependency property.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes", Justification = "This member is necessary because the base classes need to share this dependency property.")]
public static readonly DependencyProperty IndependentAxisProperty =
DependencyProperty.Register(
"IndependentAxis",
typeof(IAxis),
typeof(ColumnSeries),
new PropertyMetadata(null, OnIndependentAxisPropertyChanged));
/// <summary>
/// IndependentAxisProperty property changed handler.
/// </summary>
/// <param name="d">ColumnBarBaseSeries that changed its IndependentAxis.</param>
/// <param name="e">Event arguments.</param>
private static void OnIndependentAxisPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
CommandColumnSeries source = (CommandColumnSeries)d;
IAxis newValue = (IAxis)e.NewValue;
source.OnIndependentAxisPropertyChanged(newValue);
}
/// <summary>
/// IndependentAxisProperty property changed handler.
/// </summary>
/// <param name="newValue">New value.</param>
private void OnIndependentAxisPropertyChanged(IAxis newValue)
{
this.InternalIndependentAxis = (IAxis)newValue;
}
#endregion public IAxis IndependentAxis
public CommandColumnSeries()
{
this.SelectionChanged += new SelectionChangedEventHandler(CommandColumnSeries_SelectionChanged);
}
private void CommandColumnSeries_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
if (Command != null)
{
RoutedCommand routedCommand = Command as RoutedCommand;
CommandParameter = e.Source;
if (routedCommand != null)
{
routedCommand.Execute(CommandParameter, CommandTarget);
}
else
{
Command.Execute(CommandParameter);
}
}
}
protected override void GetAxes(DataPoint firstDataPoint)
{
// Taken from the source of the ColumnSeries sealed class.
GetAxes(
firstDataPoint,
(axis) => axis.Orientation == AxisOrientation.X,
() => new CategoryAxis { Orientation = AxisOrientation.X },
(axis) =>
{
IRangeAxis rangeAxis = axis as IRangeAxis;
return rangeAxis != null && rangeAxis.Origin != null && axis.Orientation == AxisOrientation.Y;
},
() =>
{
IRangeAxis rangeAxis = CreateRangeAxisFromData(firstDataPoint.DependentValue);
rangeAxis.Orientation = AxisOrientation.Y;
if (rangeAxis == null || rangeAxis.Origin == null)
{
throw new InvalidOperationException("No Suitable Axes found for plotting range axis.");
}
DisplayAxis axis = rangeAxis as DisplayAxis;
if (axis != null)
{
axis.ShowGridLines = true;
}
return rangeAxis;
});
}
protected override void UpdateDataPoint(DataPoint dataPoint)
{
// This code taken from the ColumnSeries sealed class.
if (SeriesHost == null )//|| PlotArea == null)
{
return;
}
object category = dataPoint.ActualIndependentValue ?? (IndexOf<DataPoint>(this.ActiveDataPoints, dataPoint) + 1);
Range<UnitValue> coordinateRange = GetCategoryRange(category);
if (!coordinateRange.HasData)
{
return;
}
else if (coordinateRange.Maximum.Unit != Unit.Pixels || coordinateRange.Minimum.Unit != Unit.Pixels)
{
throw new InvalidOperationException("This Series Does Not Support Radial Axes");
}
double minimum = (double)coordinateRange.Minimum.Value;
double maximum = (double)coordinateRange.Maximum.Value;
double plotAreaHeight = ActualDependentRangeAxis.GetPlotAreaCoordinate(ActualDependentRangeAxis.Range.Maximum).Value.Value;
IEnumerable<CommandColumnSeries> columnSeries = SeriesHost.Series.OfType<CommandColumnSeries>().Where(series => series.ActualIndependentAxis == ActualIndependentAxis);
int numberOfSeries = columnSeries.Count();
double coordinateRangeWidth = (maximum - minimum);
double segmentWidth = coordinateRangeWidth * 0.8;
double columnWidth = segmentWidth / numberOfSeries;
int seriesIndex = IndexOf<CommandColumnSeries>(columnSeries, this);
double dataPointY = ActualDependentRangeAxis.GetPlotAreaCoordinate(ToDouble(dataPoint.ActualDependentValue)).Value.Value;
double zeroPointY = ActualDependentRangeAxis.GetPlotAreaCoordinate(ActualDependentRangeAxis.Origin).Value.Value;
double offset = seriesIndex * Math.Round(columnWidth) + coordinateRangeWidth * 0.1;
double dataPointX = minimum + offset;
if (GetIsDataPointGrouped(category))
{
// Multiple DataPoints share this category; offset and overlap them appropriately
IGrouping<object, DataPoint> categoryGrouping = GetDataPointGroup(category);
int index = GroupIndexOf(categoryGrouping, dataPoint);
dataPointX += (index * (columnWidth * 0.2)) / (categoryGrouping.Count() - 1);
columnWidth *= 0.8;
Canvas.SetZIndex(dataPoint, -index);
}
if (CanGraph(dataPointY) && CanGraph(dataPointX) && CanGraph(zeroPointY))
{
double left = Math.Round(dataPointX);
double width = Math.Round(columnWidth);
double top = Math.Round(plotAreaHeight - Math.Max(dataPointY, zeroPointY) + 0.5);
double bottom = Math.Round(plotAreaHeight - Math.Min(dataPointY, zeroPointY) + 0.5);
double height = bottom - top + 1;
Canvas.SetLeft(dataPoint, left);
Canvas.SetTop(dataPoint, top);
dataPoint.Width = width;
dataPoint.Height = height;
}
}
private static int IndexOf<T>(IEnumerable<T> collection, T target)
{
int i = 0;
foreach (var obj in collection)
{
if (obj.Equals(target))
return i;
i++;
}
return -1;
}
private static int GroupIndexOf(IGrouping<object, DataPoint> group, DataPoint point)
{
int i = 0;
foreach (var pt in group)
{
if (pt == point)
return i;
i++;
}
return -1;
}
/// <summary>
/// Returns a value indicating whether this value can be graphed on a
/// linear axis.
/// </summary>
/// <param name="value">The value to evaluate.</param>
/// <returns>A value indicating whether this value can be graphed on a
/// linear axis.</returns>
private static bool CanGraph(double value)
{
return !double.IsNaN(value) && !double.IsNegativeInfinity(value) && !double.IsPositiveInfinity(value) && !double.IsInfinity(value);
}
/// <summary>
/// Converts an object into a double.
/// </summary>
/// <param name="value">The value to convert to a double.</param>
/// <returns>The converted double value.</returns>
private static double ToDouble(object value)
{
return Convert.ToDouble(value, CultureInfo.InvariantCulture);
}
}

Resources