Best way to implement margin between WPF/SL grid columns/rows - wpf

What's the best way to add margin between columns or rows in a WPF or Silverlight grid?
Add fixed width/height columns/rows to the grid
Add margin to the grid child controls
Anything else?
Thanks in advance

It depends, really, on your design, and is a matter of your own tastes. The biggest thing is to be consistent.
I think it's perfectly acceptable to put a fixed width "spacer" column or row in most cases - then you don't have to worry about maintenance later (either by you or somebody else).
The thing to watch out for is setting things twice (i.e. both a margin and fixed width column). It's not too big a problem if you are using all the same kind of control, but it could get a little ugly if you use different kinds of controls that have Styles applied to them that include Margins and/or Padding.

If you don't mind deriving your own control from the Grid and using that instead, you can do it quite easily. Since it seems like a good idea I quickly whipped up this (mostly untested and quite ugly!) code:
/// <summary>
/// Enhanced Grid that can automatically apply a padding to all its children.
/// </summary>
public class PaddedGrid : Grid
{
/// <summary>
/// Gets or sets a padding value to apply as the margin to all children.
/// If left to default (null or 'zero' Thickness) the margins of the children are not modified.
/// </summary>
public Thickness? Padding
{
get { return (Thickness?)GetValue(PaddingProperty); }
set { SetValue(PaddingProperty, value); }
}
public static readonly DependencyProperty PaddingProperty =
DependencyProperty.Register("Padding", typeof(Thickness?), typeof(PaddedGrid), new PropertyMetadata(PaddingChanged));
private bool HasPadding()
{
return Padding.HasValue && Padding.Value != default(Thickness);
}
private static void PaddingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var g = d as PaddedGrid;
if (g != null)
{
if (!g.HasPadding()) return;
for (int i = 0; i < g.VisualChildrenCount; i++)
{
var v = g.GetVisualChild(i);
var c = v as FrameworkElement;
if (c == null || c is GridSplitter) continue;
c.Margin = (Thickness)e.NewValue;
}
}
}
protected override void OnVisualChildrenChanged(DependencyObject visualAdded, DependencyObject visualRemoved)
{
base.OnVisualChildrenChanged(visualAdded, visualRemoved);
if (!HasPadding()) return;
if (visualAdded != null)
{
var fe = visualAdded as FrameworkElement;
if (fe != null) fe.Margin = this.Padding.Value;
}
}
}

Related

TreeView: Place selection indicator along the item at the left edge of the control

So the requirement is simple, but the solution doesn't seem to be (or at least I haven't succeeded yet). I need to display a vertical bar at the left side of the currently selected item of the TreeView control. Something like this:
Problem I'm facing is that with child items, this indicator also moves towards right, as it is part of the ItemTemplate, like this:
This is undesirable. I need the red indicator to stick to the left edge of the control, like this:
I can see why this happens. The ItemsPresenter in TreeViewItem template introduces a left margin of 16 units, which causes the all child items to move right-wards as well. I can't figure out how to avoid it.
Note: The red bar is a Border with StrokeThickness set to 4,0,0,0. It encompasses the Image and TextBlock elements inside it, though this doesn't directly have anything to do with the problem.
As you are aware, since the left vacant space is outside of ItemsPresenter which hosts the content of TreeViewItem, you cannot accomplish it by ordinary Style.
Instead, a workaround would be to change the bar to an element such as Rentangle and move it to the edge of TreeView. For example, it can be done by an attached property which is to be attached to the element and move it to the edge of TreeView with a specified left margin.
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
public static class TreeViewHelper
{
public static double? GetLeftMargin(DependencyObject obj)
{
return (double?)obj.GetValue(LeftMarginProperty);
}
public static void SetLeftMargin(DependencyObject obj, double value)
{
obj.SetValue(LeftMarginProperty, value);
}
public static readonly DependencyProperty LeftMarginProperty =
DependencyProperty.RegisterAttached("LeftMargin", typeof(double?), typeof(TreeViewHelper), new PropertyMetadata(null, OnValueChanged));
private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if ((d is FrameworkElement element) && (e.NewValue is double leftMargin))
{
element.Loaded += (_, _) =>
{
TreeView? tv = GetTreeView(element);
if (tv is null)
return;
Point relativePosition = element.TransformToAncestor(tv).Transform(new Point(0, 0));
element.RenderTransform = new TranslateTransform(leftMargin - relativePosition.X, 0);
};
}
}
private static TreeView? GetTreeView(FrameworkElement element)
{
DependencyObject test = element;
while (test is not null)
{
test = VisualTreeHelper.GetParent(test);
if (test is TreeView tv)
return tv;
}
return null;
}
}
Edit:
This workaround does not depend on how to show/hide the bar upon selection of the ListViewItem. Although the question does not provide the actual code for this, if you implement a mechanism to change BorderBrush upon selelection, you can modify it to change Fill of the bar (in the case of Rectangle).

Get the scroll position of a WPF TextBox

I need to add some decoration to the contents of a WPF TextBox control. That works fine basically, I can get the position of specified character indices and layout my other elements accordingly. But it all breaks when the TextBox is scrolled. My layout positions don't match with the displayed text anymore because it has moved elsewhere.
Now I'm pretty surprised that the TextBox class doesn't provide any information about its scrolling state, nor any events when the scrolling has changed. What can I do now?
I used Snoop to find out whether there is some scrolling sub-element that I could ask, but the ScrollContentPresenter also doesn't have any scrolling information available. I'd really like to put my decoration elements right into the scrolled area so that the scrolling can affect them, too, but there can only be a single content control and that's one of the TextBox internals already.
I'm not sure how to capture an event when the textbox has been scrolled (probably use narohi's answer for that), but there is a simple way to see what the current scroll position is:
// Gets or sets the vertical scroll position.
textBox.VerticalOffset
(From http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.textboxbase.verticaloffset(v=vs.100).aspx)
I'm using it to see if the textbox is scrolled to the end, like this:
public static bool IsScrolledToEnd(this TextBox textBox)
{
return textBox.VerticalOffset + textBox.ViewportHeight == textBox.ExtentHeight;
}
You can get the ScrollViewer with this method by passing in your textbox as the argument and the type ScrollView. Then you may subscribe to the ScrollChanged event.
public static T FindDescendant<T>(DependencyObject obj) where T : DependencyObject
{
if (obj == null) return default(T);
int numberChildren = VisualTreeHelper.GetChildrenCount(obj);
if (numberChildren == 0) return default(T);
for (int i = 0; i < numberChildren; i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child is T)
{
return (T)(object)child;
}
}
for (int i = 0; i < numberChildren; i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
var potentialMatch = FindDescendant<T>(child);
if (potentialMatch != default(T))
{
return potentialMatch;
}
}
return default(T);
}
Example:
public MainWindow()
{
InitializeComponent();
Loaded += new RoutedEventHandler(MainWindow_Loaded);
}
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
ScrollViewer s = FindDescendant<ScrollViewer>(txtYourTextBox);
s.ScrollChanged += new ScrollChangedEventHandler(s_ScrollChanged);
}
void s_ScrollChanged(object sender, ScrollChangedEventArgs e)
{
// check event args for information needed
}

Slider \ ScrollViewer in a touch interface not working properly

In WPF I've got the following XAML:
<ScrollViewer Canvas.Left="2266" Canvas.Top="428" Height="378" Name="scrollViewer1" Width="728" PanningMode="VerticalOnly" PanningRatio="2">
<Canvas Height="1732.593" Width="507.667">
<Slider Height="40.668" x:Name="slider1" Width="507.667" Style="{DynamicResource SliderStyle1}" Canvas.Left="15" Canvas.Top="150" />
</Slider>
</Canvas>
</ScrollViewer>
It's a ScrollViewer containing a Slider. I'm using the following on a touch-screen, and I'm using the panning even to scroll the ScrollViewer vertically. When PanningMode="VerticalOnly" is set, the slider stops working!
I'm assuming the ScollViewer is consuming the touch\slide event and handling it before the slider does (but I think I'm wrong on this front).
Is there any workaround for this?
I just solved this issue in our app.
What is happening is that the ScrollViewer captures the TouchDevice in its PreviewTouchMove handler, which "steals" the TouchDevice from other controls and prevents them from receiving any PreviewTouchMove or TouchMove events.
In order to work around this, you need to implement a custom Thumb control that captures the TouchDevice in the PreviewTouchDown event and stores a reference to it until the PreviewTouchUp event occurs. Then the control can "steal" the capture back in its LostTouchCapture handler, when appropriate. Here is some brief code:
public class CustomThumb : Thumb
{
private TouchDevice currentDevice = null;
protected override void OnPreviewTouchDown(TouchEventArgs e)
{
// Release any previous capture
ReleaseCurrentDevice();
// Capture the new touch
CaptureCurrentDevice(e);
}
protected override void OnPreviewTouchUp(TouchEventArgs e)
{
ReleaseCurrentDevice();
}
protected override void OnLostTouchCapture(TouchEventArgs e)
{
// Only re-capture if the reference is not null
// This way we avoid re-capturing after calling ReleaseCurrentDevice()
if (currentDevice != null)
{
CaptureCurrentDevice(e);
}
}
private void ReleaseCurrentDevice()
{
if (currentDevice != null)
{
// Set the reference to null so that we don't re-capture in the OnLostTouchCapture() method
var temp = currentDevice;
currentDevice = null;
ReleaseTouchCapture(temp);
}
}
private void CaptureCurrentDevice(TouchEventArgs e)
{
bool gotTouch = CaptureTouch(e.TouchDevice);
if (gotTouch)
{
currentDevice = e.TouchDevice;
}
}
}
Then you will need to re-template the Slider to use the CustomThumb instead of the default Thumb control.
i strugled with a similar issue. the workaround was this one (none of the others worked for me): i created a custom thumb, and then i used it inside a scrollbar style in xaml as the PART_Track's thumb.
public class DragableThumb : Thumb
{
double m_originalOffset;
double m_originalDistance;
int m_touchID;
/// <summary>
/// Get the parent scrollviewer, if any
/// </summary>
/// <returns>Scroll viewer or null</returns>
ScrollViewer GetScrollViewer()
{
if (TemplatedParent is ScrollBar && ((ScrollBar)TemplatedParent).TemplatedParent is ScrollViewer)
{
return ((ScrollViewer)((ScrollBar)TemplatedParent).TemplatedParent);
}
return null;
}
/// <summary>
/// Begin thumb drag
/// </summary>
/// <param name="e">Event arguments</param>
protected override void OnTouchDown(TouchEventArgs e)
{
ScrollViewer scrollViewer;
base.OnTouchDown(e);
m_touchID = e.TouchDevice.Id;
if ((scrollViewer = GetScrollViewer()) != null)
{
m_originalOffset = scrollViewer.HorizontalOffset;
m_originalDistance = e.GetTouchPoint(scrollViewer).Position.X;
}
}
/// <summary>
/// Handle thumb delta
/// </summary>
/// <param name="e">Event arguments</param>
protected override void OnTouchMove(TouchEventArgs e)
{
ScrollViewer scrollViewer;
double actualDistance;
base.OnTouchMove(e);
if ((scrollViewer = GetScrollViewer()) != null && m_touchID == e.TouchDevice.Id)
{
actualDistance = e.GetTouchPoint(scrollViewer).Position.X;
scrollViewer.ScrollToHorizontalOffset(m_originalOffset + (actualDistance - m_originalDistance) * scrollViewer.ExtentWidth / scrollViewer.ActualWidth);
}
}
}
The following worked for me. I searched around for a long time for something that would work. I adapted this for touch from How to make WPF Slider Thumb follow cursor from any point. This is a much simpler fix and allows you to avoid creating a custom slider/thumb control.
<Slider TouchMove="OnTouchMove" IsMoveToPointEnabled="True"/>
IsMoveToPointEnable must be set to true for this to work.
private void Slider_OnTouchMove(object sender, TouchEventArgs e)
{
Slider slider = (Slider)sender;
TouchPoint point = e.GetTouchPoint (slider );
double d = 1.0 / slider.ActualWidth * point.Position.X;
int p = int(slider.Maximum * d);
slider.Value = p;
}
This is nice and simple and worked for me - although it's worth wrapping up in a generic function and extending to handle the slider minimum value also as it may not be zero. What a pain to have to do though. There are many thing about WPF that are cool, but so many simple things require extra steps it really can be detrimental to productivity.

WPF ListView columns dont update thair width in time [duplicate]

I have a ListView WPF control with a GridView. I'd like to resize the GridView columns when the content of the columns changes.
I have several distinct data sets but when I change from one to another, the size of each columns fits the previous data. I'd like to update dynamically. How can I do that?
Finally, some results on this one. I've found a way to do the same auto-sizing that is done initially and when the gripper on a column header is double clicked.
public void AutoSizeColumns()
{
GridView gv = listView1.View as GridView;
if (gv != null)
{
foreach (var c in gv.Columns)
{
// Code below was found in GridViewColumnHeader.OnGripperDoubleClicked() event handler (using Reflector)
// i.e. it is the same code that is executed when the gripper is double clicked
if (double.IsNaN(c.Width))
{
c.Width = c.ActualWidth;
}
c.Width = double.NaN;
}
}
}
Building on top of Oskars answer, here is a blend behavior to automatically size the columns when the content changes.
/// <summary>
/// A <see cref="Behavior{T}"/> implementation which will automatically resize the automatic columns of a <see cref="ListView">ListViews</see> <see cref="GridView"/> to the new content.
/// </summary>
public class GridViewColumnResizeBehaviour : Behavior<ListView>
{
/// <summary>
/// Listens for when the <see cref="ItemsControl.Items"/> collection changes.
/// </summary>
protected override void OnAttached()
{
base.OnAttached();
var listView = AssociatedObject;
if (listView == null)
return;
AddHandler(listView.Items);
}
private void AddHandler(INotifyCollectionChanged sourceCollection)
{
Contract.Requires(sourceCollection != null);
sourceCollection.CollectionChanged += OnListViewItemsCollectionChanged;
}
private void RemoveHandler(INotifyCollectionChanged sourceCollection)
{
Contract.Requires(sourceCollection != null);
sourceCollection.CollectionChanged -= OnListViewItemsCollectionChanged;
}
private void OnListViewItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs)
{
var listView = AssociatedObject;
if (listView == null)
return;
var gridView = listView.View as GridView;
if (gridView == null)
return;
// If the column is automatically sized, change the column width to re-apply automatic width
foreach (var column in gridView.Columns.Where(column => Double.IsNaN(column.Width)))
{
Contract.Assume(column != null);
column.Width = column.ActualWidth;
column.Width = Double.NaN;
}
}
/// <summary>
/// Stops listening for when the <see cref="ItemsControl.Items"/> collection changes.
/// </summary>
protected override void OnDetaching()
{
var listView = AssociatedObject;
if (listView != null)
RemoveHandler(listView.Items);
base.OnDetaching();
}
}
If like me you are old and prefer VB.NET then here's Oskars code:
Public Sub AutoSizeColumns()
Dim gv As GridView = TryCast(Me.listview1.View, GridView)
If gv IsNot Nothing Then
For Each c As GridViewColumn In gv.Columns
If Double.IsNaN(c.Width) Then
c.Width = c.ActualWidth
End If
c.Width = Double.NaN
Next
End If
End Sub
This works great in WPF, finally someone has worked this out. Thanks Oskar.
Isn't there a way to bind to the ActualWidth of the column? Something like :
<GridViewColumn x:Name="column1" Width="{Binding ElementName=column1, Path=ActualWidth}" />
I have tried this and it works only the first time, it seems. No binding error.
You could measure the longest string in pixels and then adjust the column widths accordingly:
Graphics graphics = this.CreateGraphics();
SizeF textSize = graphics.MeasureString("How long am I?", this.Font);
If you create an algorithm for sizing each column as a ratio of these lengths, you should get a good result.

Programmatically create ItemsPanelTemplate for Silverlight ComboBox?

I am trying to create a Blend behavior related to ComboBoxes. In order to get the effect I want, the ItemsPanel of the ComboBox has to have a certain element added to it. I don't want to do this in every ComboBox that uses the behavior, so I want the Behavior to be able to inject the ItemsPanelTemplate programmatically. However, I can't seem to find a way to do this. ItemsPanelTemplate does not seem to have a property/method that lets me set the visual tree. WPF ItemsPanelTemplate has the VisualTree but Silverlight does not.
Basically, what is the programmatic equivalent of this XAML?
<ComboBox>
<ComboBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel/>
</ItemsPanelTemplate>
</ComboBox.ItemsPanel>
</ComboBox>
Edit:
Okay apparently that is not an easy question, so I started a bounty and I'm going to give some more background in case there is another way to go about this. I want to provide keyboard support for the Silverlight ComoboBox. Out of the box it only supports the up and down arrows but I also want it to work so that when the user hits a letter, the ComboBox jumps to the first item of that letter, similar to how ComboBoxes work in a browser or Windows app.
I found this blog post, which got me half way. Adapting that behavior code, the ComboBox will change selection based on letter input. However, it does not work when the ComboBox is opened. The reason for this, according to this blog post is that when the ComboBox is opened, you are now interacting with its ItemsPanel and not the ComboBox itself. So according to that post I actually need to add a StackPanel to the ItemsPanelTemplate and subscribe to the StackPanel's KeyDown event, in order to take action when the ComboBox is opened.
So that is what prompted my question of how to get a StackPanel into the ItemsPanelTemplate of a ComboBox, from a behavior. If that is not possible, are there alternative ways of getting this to work? Yes, I know I could go to each ComboBox in the application and add a StackPanel and the event. But I want to do this through a behavior so that I don't have to modify every ComboBox in the app, and so I can reuse this logic across applications.
AnthonyWJones' answer below using XamlReader gets me part way, in that I can create the StackPanel and get it into the template. However, I need to be able to get at that SP programmatically in order to subscribe to the event.
This should work. I've shown how you can change the orientation below. You can add additional SetValue calls to modify other properties.
cb.ItemsPanel = new ItemsPanelTemplate();
var stackPanelFactory = new FrameworkElementFactory(typeof (StackPanel));
// Modify it like this:
stackPanelFactory.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
// Set the root of the template to the stack panel factory:
cb.ItemsPanel.VisualTree = stackPanelFactory;
You can find more detailed information in this article: http://www.codeproject.com/KB/WPF/codeVsXAML.aspx
What you actually want to build programmatically is this:-
<ItemsPanelTemplate>
<StackPanel />
</ItemsPanelTemplate>
Your behaviour will then assign this to the ItemsPanel property of the ComboBox it is attached to. Currently your behaviour is pure code but there is no way to create the above purely in code.
Since this is such a small piece for of Xaml the easiest approach is to use the XamlReader:-
ItemsPanelTemplate itemsPanelTemplate = XamlReader.Load("<ItemsPanelTemplate><StackPanel /></ItemsPanelTemplate>");
I think, best way for you - extend combobox functionality not via behavior but using inheritance.
So, you can create own control MyComboBox:ComboBox. Create style for it - get default ComboBox Style
here
And write instead (look for ScrollViewer by name):
< ScrollViewer x:Name="ScrollViewer" BorderThickness="0" Padding="1" >
< ItemsPresenter />
< /ScrollViewer >
this
< ScrollViewer x:Name="ScrollViewer" BorderThickness="0" Padding="1" >
< StackPanel x:Name="StackPanel" >
< ItemsPresenter />
< /StackPanel >
< /ScrollViewer >
This StackPanel you can get in code:
public class MyComboBox: ComboBox{
public CM()
{
DefaultStyleKey = typeof (MyComboBox);
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
StackPanel stackPanel = (StackPanel)GetTemplateChild("StackPanel");
stackPanel.KeyUp += (s, e) => { /*do something*/ };
}
}
Inheritance is more powerful. It's allow work with template elements.
If you decided to inject ItemsPanel, you must understand that:
1)it's impossible from code with keeping reference on injected panel.
2)to get reference to injected panel, this panel must registered itself in some storage, e.g.
< ComboBox>
< ComboBox.ItemsPanel>
< ItemsPanelTemplate>
< StackPanel>
< i:Interaction.EventTriggers>
< i:EventTrigger EventName="Loaded">
< RegisterMyInstanceInAccessibleFromCodePlaceAction/>
< /i:EventTrigger>
< /i:Interaction.EventTriggers>
< /StackPanel>
< /ItemsPanelTemplate>
< /ComboBox.ItemsPanel>
< /ComboBox>
Good luck!
I found your post while trying to set the ItemsPanel from code so that I can implement a VirtualizingStackPanel. When there are hundreds of items in my list, performance sucks. Anyway .. here's how I did it.
1) Custom control
2) Custom Behavior
-- you could also just apply this behavior to the normal ComboBox - either at each instance, or through a style.
-- you might also expose the timeout value so that can be overridden in xaml ..
-- also, it seems this doesn't work when the dropdown itself is open. not sure why exactly .. never looked into it
1..
public class KeyPressSelectionComboBox : ComboBox
{
private BindingExpression _bindingExpression;
public KeyPressSelectionComboBox()
: base()
{
Interaction.GetBehaviors(this).Add(new KeyPressSelectionBehavior());
Height = 22;
this.SelectionChanged += new SelectionChangedEventHandler(KeyPressSelectionComboBox_SelectionChanged);
}
void KeyPressSelectionComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_bindingExpression == null)
{
_bindingExpression = this.GetBindingExpression(ComboBox.SelectedValueProperty);
}
else
{
if (this.GetBindingExpression(ComboBox.SelectedValueProperty) == null)
{
this.SetBinding(ComboBox.SelectedValueProperty, _bindingExpression.ParentBinding);
}
}
}
}
2...
/// <summary>
/// This behavior can be attached to a ListBox or ComboBox to
/// add keyboard selection
/// </summary>
public class KeyPressSelectionBehavior : Behavior<Selector>
{
private string keyDownHistory = string.Empty;
private double _keyDownTimeout = 2500;
private DateTime _lastKeyDownTime;
private DateTime LastKeyDownTime
{
get
{
if (this._lastKeyDownTime == null)
this._lastKeyDownTime = DateTime.Now;
return this._lastKeyDownTime;
}
set { _lastKeyDownTime = value; }
}
/// <summary>
/// Gets or sets the Path used to select the text
/// </summary>
public string SelectionMemberPath { get; set; }
/// <summary>
/// Gets or sets the Timeout (ms) used to reset the KeyDownHistory item search string
/// </summary>
public double KeyDownTimeout
{
get { return _keyDownTimeout; }
set { _keyDownTimeout = value; }
}
public KeyPressSelectionBehavior() { }
/// <summary>
/// Attaches to the specified object: subscribe on KeyDown event
/// </summary>
protected override void OnAttached()
{
base.OnAttached();
this.AssociatedObject.KeyDown += DoKeyDown;
}
void DoKeyDown(object sender, KeyEventArgs e)
{
// Create a list of strings and indexes
int index = 0;
IEnumerable<Item> list = null;
var path = SelectionMemberPath ??
this.AssociatedObject.DisplayMemberPath;
var evaluator = new BindingEvaluator();
if (path != null)
{
list = this.AssociatedObject.Items.OfType<object>()
.Select(item =>
{
// retrieve the value using the supplied Path
var binding = new Binding();
binding.Path = new PropertyPath(path);
binding.Source = item;
BindingOperations.SetBinding(evaluator,
BindingEvaluator.TargetProperty, binding);
var value = evaluator.Target;
return new Item
{
Index = index++,
Text = Convert.ToString(value)
};
});
}
else
{
list = this.AssociatedObject.Items.OfType<ListBoxItem>()
.Select(item => new Item
{
Index = index++,
Text = Convert.ToString(item.Content)
});
}
// Sort the list starting at next selectedIndex to the end and
// then from the beginning
list = list.OrderBy(item => item.Index <=
this.AssociatedObject.SelectedIndex ?
item.Index + this.AssociatedObject.Items.Count : item.Index);
// calculate how long has passed since the user typed a letter
var elapsedTime = DateTime.Now - this.LastKeyDownTime;
if (elapsedTime.TotalMilliseconds <= this.KeyDownTimeout)
{ /* if it's less than the timeout, add to the search string */
this.keyDownHistory += GetKeyValue(e);
}
else
{ /* otherwise replace it */
this.keyDownHistory = GetKeyValue(e);
}
// Find first starting with the search string
var searchText = this.keyDownHistory;
var first = list.FirstOrDefault(item =>
item.Text.StartsWith(searchText, StringComparison.InvariantCultureIgnoreCase));
if (first != null)
{ /* found */
this.AssociatedObject.SelectedIndex = first.Index;
}
else
{ /* not found - so reset the KeyDownHistory */
this.keyDownHistory = string.Empty;
}
// reset the last time a key was pressed
this.LastKeyDownTime = DateTime.Now;
}
/// <summary>
/// Gets the value of the pressed key,
/// specifically converting number keys from their "Dx" value to their expected "x" value
/// </summary>
/// <param name="e"></param>
/// <returns></returns>
private static string GetKeyValue(KeyEventArgs e)
{
string rValue = string.Empty;
switch (e.Key)
{
default:
rValue = e.Key.ToString();
break;
case Key.D0:
case Key.NumPad0:
rValue = (0).ToString();
break;
case Key.D1:
case Key.NumPad1:
rValue = (1).ToString();
break;
case Key.D2:
case Key.NumPad2:
rValue = (2).ToString();
break;
case Key.D3:
case Key.NumPad3:
rValue = (3).ToString();
break;
case Key.D4:
case Key.NumPad4:
rValue = (4).ToString();
break;
case Key.D5:
case Key.NumPad5:
rValue = (5).ToString();
break;
case Key.D6:
case Key.NumPad6:
rValue = (6).ToString();
break;
case Key.D7:
case Key.NumPad7:
rValue = (7).ToString();
break;
case Key.D8:
case Key.NumPad8:
rValue = (8).ToString();
break;
case Key.D9:
case Key.NumPad9:
rValue = (9).ToString();
break;
}
return rValue;
}
/// <summary>
/// Helper class
/// </summary>
private class Item
{
public int Index;
public string Text;
}
/// <summary>
/// Helper class used for property path value retrieval
/// </summary>
private class BindingEvaluator : FrameworkElement
{
public static readonly DependencyProperty TargetProperty =
DependencyProperty.Register(
"Target",
typeof(object),
typeof(BindingEvaluator), null);
public object Target
{
get { return GetValue(TargetProperty); }
set { SetValue(TargetProperty, value); }
}
}
}

Resources