Outlook-style Spacebar reading with WPF and MVVM - wpf

One great feature of Microsoft Outlook is its spacebar reading mode (with the reading pane turned on). Say there are 5 messages in your inbox and the first one is displayed. The displayed message does not entirely fit on the screen, so when you press the spacebar, that is like pagedown within the message. You hit spacebar again, and it pages down again. When you've reached the bottom of the page, and you press spacebar again, it goes to the next message.
What is a good way to do this in WPF (where the application is built using the MVVM pattern)? With MVVM, I use a bunch of DataTemplates instead of usercontrols.
Edit: I should mention that I am using a ListBox for the messages and a FlowDocumentScrollViewer for the message body.

Use Expression Blend's KeyTrigger to invoke the Command in your view model
http://msdn.microsoft.com/en-us/library/microsoft.expression.interactivity.input.keytrigger%28v=expression.40%29.aspx
OR
Use CommandReference from MVVM Toolkit How do I associate a keypress with a DelegateCommand in Composite WPF?

For posterity, here's my solution to the scrolling part of the question. This code handles the space first, then, if the scroll bar is already at the bottom, it doesn't handle the KeyDown. #Hasan's recomended commend fires at that point.
internal class FlowDocumentScrollViewer2 : FlowDocumentScrollViewer
{
private static bool PageDown<T>(T listView)
where T : DependencyObject
{
var scrollViewer = GetVisualChild<ScrollViewer>(listView, null);
var scrollBar = GetVisualChild<ScrollBar>(listView,
bar => bar.Orientation == Orientation.Vertical);
var formerOffset = scrollBar.Track.Value;
scrollViewer.PageDown();
scrollBar.Track.UpdateLayout();
return formerOffset < scrollBar.Track.Value;
}
private static T GetVisualChild<T>(DependencyObject parent, Predicate<T> predicate)
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(v, predicate);
}
if (child != null && (predicate == null || predicate(child)))
{
break;
}
}
return child;
}
public FlowDocumentScrollViewer2()
{
PreviewKeyDown += PreviewSpaceDown;
}
private void PreviewSpaceDown(object sender, KeyEventArgs e)
{
if (e.Handled)
return;
if (e.Key == Key.Space)
{
e.Handled = PageDown(this);
}
}
}

Related

WPF ComboBox KeyUp Event for all comboboxes

i have a WPF Application with 50 comboboxes. When i started to write this application a month ago, i forgot to add a KeyUp event to all comboboxes...
Is there a way of adding this event without going to each comboboxes and write xaml code ?
<ComboBox x:Name="Actif_Vent_CB" Grid.Column="1"
SelectionChanged="Actif_Vent_CB_SelectionChanged"
KeyUp="Actif_Vent_CB_KeyUp"/>
private void Actif_Vent_CB_KeyUp(object sender, KeyEventArgs e)
{
switch (e.Key)
{
default:
break;
case Key.Delete:
case Key.Back:
((ComboBox)sender).SelectedIndex = -1;
break;
}
}
With a Dictionary ?? or something else ??
Thank you for your help
You can traverse through the layout one by one and check if the element is ComboBox and assign event listeners to them.
Call the following method in the Loaded event of your window and pass current window as visual.
public void SetEventToComboBox(Visual myVisual)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(myVisual); i++)
{
// Retrieve child visual at specified index value.
Visual childVisual = (Visual)VisualTreeHelper.GetChild(myVisual, i);
// Do processing of the child visual object.
if (childVisual is ComboBox)
{
((ComboBox)childVisual).KeyUp += Actif_Vent_CB_KeyUp;
}
// Enumerate children of the child visual object.
SetEventToComboBox(childVisual);
}
}
Source:
MSDN Documentation

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
}

Record items visible to user in ListBox

I have a ListBox or DataGrid filled with thousands of entries. I would like to know items that the user has looked at (scrolling, searching or otherwise). How can I tell what is visible to the user in the ListBox?
Bonus: Set a timer so that the item has to be shown for a minimum of N milliseconds (in the event the user is just pulling down the scrollbar).
Update: This is a near duplicate of Get items in view within a listbox - but the solution it gives, using "SelectedItems", is not sufficient. I need to know the items whether they are selected or not!
All you need to do is to get the underlying StackPanel that's inside the ListBox. It has enough information about which elements are showing. (It implements the interface IScrollInfo).
To get the underlying StackPanel (or actually VirtualizingStackPanel) from a given ListBox, we'll have to use VisualTreeHelper to go through the Visual Tree and look for the VirtualizingStackPanel, like so:
private VirtualizingStackPanel GetInnerStackPanel(FrameworkElement element)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++)
{
var child = VisualTreeHelper.GetChild(element, i) as FrameworkElement;
if (child == null) continue;
Debug.WriteLine(child.ToString());
if (child is VirtualizingStackPanel) return child as VirtualizingStackPanel;
var panel = GetInnerStackPanel(child);
if (panel != null)
return panel;
}
return null;
}
Now that we have the StackPanel, we're very close. The StackPanel has the properties VerticalOffset and ViewportHeight (both coming from IScrollInfo) that can give us all the information we need.
private void button1_Click(object sender, RoutedEventArgs e)
{
var theStackPanel = GetInnerStackPanel(MyListBox);
List<FrameworkElement> visibleElements = new List<FrameworkElement>();
for (int i = 0; i < theStackPanel.Children.Count; i++)
{
if (i >= theStackPanel.VerticalOffset && i <= theStackPanel.VerticalOffset + theStackPanel.ViewportHeight)
{
visibleElements.Add(theStackPanel.Children[i] as FrameworkElement);
}
}
MessageBox.Show(visibleElements.Count.ToString());
MessageBox.Show(theStackPanel.VerticalOffset.ToString());
MessageBox.Show((theStackPanel.VerticalOffset + theStackPanel.ViewportHeight).ToString());
}

WinForms ListBox with readonly/disabled items

Is there a way to make some of the items in a ListBox readonly/disabled so they can't be selected? Or are there any similar controls to ListBox to provide this functionality?
ListBox doesn't have support for that. You can bolt something on, you could deselect a selected item. Here's a silly example that prevents even-numbered items from being selected:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e) {
for (int ix = listBox1.SelectedIndices.Count - 1; ix >= 0; ix--) {
if (listBox1.SelectedIndices[ix] % 2 != 0)
listBox1.SelectedIndices.Remove(listBox1.SelectedIndices[ix]);
}
}
But the flicker is quite noticeable and it messes up keyboard navigation. You can get better results by using CheckedListBox, you can prevent the user from checking the box for an item:
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e) {
if (e.Index % 2 != 0) e.NewValue = CheckState.Unchecked;
}
But now you cannot override drawing to make it look obvious to the user that the item isn't selectable. No great solutions here, it is far simpler to just not display items in the box that shouldn't be selectable.
#Hans solution causing that the item id selected for a short time and then selection disappearing. I don't like that - this can be confusing for the enduser.
I prefer to hide some edit option buttons for the item that should be disabled:
if (lbSystemUsers.Items.Count > 0 && lbSystemUsers.SelectedIndices.Count > 0)
if (((RemoteSystemUserListEntity)lbSystemUsers.SelectedItem).Value == appLogin)
{
bSystemUsersDelete.Visible = false;
bSystemUsersEdit.Visible = false;
}
else
{
bSystemUsersDelete.Visible = true;
bSystemUsersEdit.Visible = true;
}
Here is the list that lists the users and disallow to edit user that is actually logged in to the edit panel.
ListBox doesn't have a ReadOnly (or similar) property, but you can make a custom ListBox control. Here's a solution that worked pretty well for me:
https://ajeethtechnotes.blogspot.com/2009/02/readonly-listbox.html
public class ReadOnlyListBox : ListBox
{
private bool _readOnly = false;
public bool ReadOnly
{
get { return _readOnly; }
set { _readOnly = value; }
}
protected override void DefWndProc(ref Message m)
{
// If ReadOnly is set to true, then block any messages
// to the selection area from the mouse or keyboard.
// Let all other messages pass through to the
// Windows default implementation of DefWndProc.
if (!_readOnly || ((m.Msg <= 0x0200 || m.Msg >= 0x020E)
&& (m.Msg <= 0x0100 || m.Msg >= 0x0109)
&& m.Msg != 0x2111
&& m.Msg != 0x87))
{
base.DefWndProc(ref m);
}
}
}
I know this is old thread, but i'll post a workaround for other readers in future.
listBox.Enabled = false;
listBox.BackColor = Color.LightGray;
This will change background color of list box to Light Gray. So this is not builtin "native way" to do it, but at least gives user some feedback that he is not supposed to / can't edit that field.
To get read-only behaviour I have MyCBLLocked, a boolean associated with the MyCBL checkbox list control, and on the CheckItem event I do:
private void MyCBL_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (MyCBLLocked)
e.NewValue = e.CurrentValue;
}
So instead of
MyCBL.Enabled = false;
I use
MyCBLLocked = true;
and the user can scroll through the many selections but not mess things up with changes.

How to create input gesture for page/window from an user control

I have a reusable usercontrol that uses a few commands and corresponding keyboard gestures,
(specifically Escape and Ctrl+1...Ctrl+9)
Now as I use this usercontrol in multiple locations I'd like to define the input gestures in the usercontrol, which works fine as long as the focus is within the usercontrol. However, I'd need it to work as long as focus is within the current page/window.
How can I do it, or do I really have to do command/input bindings on every page?
You could handle the Loaded event of the UserControl and walk up the logical tree to find the owning page/window, then you can add the bindings there.
e.g.
public partial class Bogus : UserControl
{
public Bogus()
{
Loaded += (s, e) => { HookIntoWindow(); };
InitializeComponent();
}
private void HookIntoWindow()
{
var current = this.Parent;
while (!(current is Window) && current is FrameworkElement)
{
current = ((FrameworkElement)current).Parent;
}
if (current != null)
{
var window = current as Window;
// Add input bindings
var command = new AlertCommand();
window.InputBindings.Add(new InputBinding(command, new KeyGesture(Key.D1, ModifierKeys.Control)));
}
}
}

Resources