Is there a way to add a button control to a cell in inside a ListView in a WinForms app?
Here is a code of a class ListViewExtender that you can reuse. It's not a derived class of ListView, basically you just declare that a specific column is displayed as buttons instead of text. The button's text is the subItem's text.
It allows big sized list views without problems, does not use p/invoke, and also works with horizontal scrollbars (some code proposed as answers here don't or are quite slow with a great number of items). Note it requires the extended ListView to have FullRowSelect set to true and view type set to Details.
This is a sample code that uses it:
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent(); // you need to add a listView named listView1 with the designer
listView1.FullRowSelect = true;
ListViewExtender extender = new ListViewExtender(listView1);
// extend 2nd column
ListViewButtonColumn buttonAction = new ListViewButtonColumn(1);
buttonAction.Click += OnButtonActionClick;
buttonAction.FixedWidth = true;
extender.AddColumn(buttonAction);
for (int i = 0; i < 10000; i++)
{
ListViewItem item = listView1.Items.Add("item" + i);
item.SubItems.Add("button " + i);
}
}
private void OnButtonActionClick(object sender, ListViewColumnMouseEventArgs e)
{
MessageBox.Show(this, #"you clicked " + e.SubItem.Text);
}
}
}
Here is the ListViewExtender code and associated classes:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
namespace WindowsFormsApplication1
{
public class ListViewExtender : IDisposable
{
private readonly Dictionary<int, ListViewColumn> _columns = new Dictionary<int, ListViewColumn>();
public ListViewExtender(ListView listView)
{
if (listView == null)
throw new ArgumentNullException("listView");
if (listView.View != View.Details)
throw new ArgumentException(null, "listView");
ListView = listView;
ListView.OwnerDraw = true;
ListView.DrawItem += OnDrawItem;
ListView.DrawSubItem += OnDrawSubItem;
ListView.DrawColumnHeader += OnDrawColumnHeader;
ListView.MouseMove += OnMouseMove;
ListView.MouseClick += OnMouseClick;
Font = new Font(ListView.Font.FontFamily, ListView.Font.Size - 2);
}
public virtual Font Font { get; private set; }
public ListView ListView { get; private set; }
protected virtual void OnMouseClick(object sender, MouseEventArgs e)
{
ListViewItem item;
ListViewItem.ListViewSubItem sub;
ListViewColumn column = GetColumnAt(e.X, e.Y, out item, out sub);
if (column != null)
{
column.MouseClick(e, item, sub);
}
}
public ListViewColumn GetColumnAt(int x, int y, out ListViewItem item, out ListViewItem.ListViewSubItem subItem)
{
subItem = null;
item = ListView.GetItemAt(x, y);
if (item == null)
return null;
subItem = item.GetSubItemAt(x, y);
if (subItem == null)
return null;
for (int i = 0; i < item.SubItems.Count; i++)
{
if (item.SubItems[i] == subItem)
return GetColumn(i);
}
return null;
}
protected virtual void OnMouseMove(object sender, MouseEventArgs e)
{
ListViewItem item;
ListViewItem.ListViewSubItem sub;
ListViewColumn column = GetColumnAt(e.X, e.Y, out item, out sub);
if (column != null)
{
column.Invalidate(item, sub);
return;
}
if (item != null)
{
ListView.Invalidate(item.Bounds);
}
}
protected virtual void OnDrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
{
e.DrawDefault = true;
}
protected virtual void OnDrawSubItem(object sender, DrawListViewSubItemEventArgs e)
{
ListViewColumn column = GetColumn(e.ColumnIndex);
if (column == null)
{
e.DrawDefault = true;
return;
}
column.Draw(e);
}
protected virtual void OnDrawItem(object sender, DrawListViewItemEventArgs e)
{
// do nothing
}
public void AddColumn(ListViewColumn column)
{
if (column == null)
throw new ArgumentNullException("column");
column.Extender = this;
_columns[column.ColumnIndex] = column;
}
public ListViewColumn GetColumn(int index)
{
ListViewColumn column;
return _columns.TryGetValue(index, out column) ? column : null;
}
public IEnumerable<ListViewColumn> Columns
{
get
{
return _columns.Values;
}
}
public virtual void Dispose()
{
if (Font != null)
{
Font.Dispose();
Font = null;
}
}
}
public abstract class ListViewColumn
{
public event EventHandler<ListViewColumnMouseEventArgs> Click;
protected ListViewColumn(int columnIndex)
{
if (columnIndex < 0)
throw new ArgumentException(null, "columnIndex");
ColumnIndex = columnIndex;
}
public virtual ListViewExtender Extender { get; protected internal set; }
public int ColumnIndex { get; private set; }
public virtual Font Font
{
get
{
return Extender == null ? null : Extender.Font;
}
}
public ListView ListView
{
get
{
return Extender == null ? null : Extender.ListView;
}
}
public abstract void Draw(DrawListViewSubItemEventArgs e);
public virtual void MouseClick(MouseEventArgs e, ListViewItem item, ListViewItem.ListViewSubItem subItem)
{
if (Click != null)
{
Click(this, new ListViewColumnMouseEventArgs(e, item, subItem));
}
}
public virtual void Invalidate(ListViewItem item, ListViewItem.ListViewSubItem subItem)
{
if (Extender != null)
{
Extender.ListView.Invalidate(subItem.Bounds);
}
}
}
public class ListViewColumnMouseEventArgs : MouseEventArgs
{
public ListViewColumnMouseEventArgs(MouseEventArgs e, ListViewItem item, ListViewItem.ListViewSubItem subItem)
: base(e.Button, e.Clicks, e.X, e.Y, e.Delta)
{
Item = item;
SubItem = subItem;
}
public ListViewItem Item { get; private set; }
public ListViewItem.ListViewSubItem SubItem { get; private set; }
}
public class ListViewButtonColumn : ListViewColumn
{
private Rectangle _hot = Rectangle.Empty;
public ListViewButtonColumn(int columnIndex)
: base(columnIndex)
{
}
public bool FixedWidth { get; set; }
public bool DrawIfEmpty { get; set; }
public override ListViewExtender Extender
{
get
{
return base.Extender;
}
protected internal set
{
base.Extender = value;
if (FixedWidth)
{
base.Extender.ListView.ColumnWidthChanging += OnColumnWidthChanging;
}
}
}
protected virtual void OnColumnWidthChanging(object sender, ColumnWidthChangingEventArgs e)
{
if (e.ColumnIndex == ColumnIndex)
{
e.Cancel = true;
e.NewWidth = ListView.Columns[e.ColumnIndex].Width;
}
}
public override void Draw(DrawListViewSubItemEventArgs e)
{
if (_hot != Rectangle.Empty)
{
if (_hot != e.Bounds)
{
ListView.Invalidate(_hot);
_hot = Rectangle.Empty;
}
}
if ((!DrawIfEmpty) && (string.IsNullOrEmpty(e.SubItem.Text)))
return;
Point mouse = e.Item.ListView.PointToClient(Control.MousePosition);
if ((ListView.GetItemAt(mouse.X, mouse.Y) == e.Item) && (e.Item.GetSubItemAt(mouse.X, mouse.Y) == e.SubItem))
{
ButtonRenderer.DrawButton(e.Graphics, e.Bounds, e.SubItem.Text, Font, true, PushButtonState.Hot);
_hot = e.Bounds;
}
else
{
ButtonRenderer.DrawButton(e.Graphics, e.Bounds, e.SubItem.Text, Font, false, PushButtonState.Default);
}
}
}
}
The ListView itself (or ListViewItem) does not function as a container of any kind so no way to add controls directly, however it is doable. I have used this extended ListView with a lot of success: Embedding Controls in a ListView.
This is the BEST custom listview control for WinForms.
ObjectListView
To make the extender of Simon Mourier working is missing the following line:
extender.AddColumn(buttonAction);
This is, it should look like:
ListViewExtender extender = new ListViewExtender(listSummary);
ListViewButtonColumn buttonAction = new ListViewButtonColumn(2);
buttonAction.Click += OnButtonActionClick;
buttonAction.FixedWidth = true;
extender.AddColumn(buttonAction);
Maybe this could be of interest?
http://www.codeproject.com/KB/list/extendedlistviews.aspx
No, a standard Windows Forms ListView doesn't support embedded controls. You could try to build your own custom control, or you could use something like http://www.codeproject.com/KB/list/EXListView.aspx.
No and yes, ListView itself does not support such functionality, but you can create a button on top of it, so that it appears to the user as integral part of the listview. (I suppose this is what the ExtendedListView mentioned above does too).
Maybe it worths mentioning, the list view control might be designed in WPF as an usercontrol/custom control with buttons in its ListViewItems, and then use this control in the WinForms application, in an ElementHost control.
I accidentally come across a discussion before, hope this help: http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/ee232cc4-68c5-4ed3-9ea7-d4d999956504/
You could use a GlacialList. It allow you to put ANY control inside a list cell and it's simple to use. You will just need to join a GlacialList.dll document to the reference part of your Solution. If you click the link it will show you how it works and how to use it and download it.
If you have a System.IO.FileNotFoundException on the InitializeComponent() just download source code from the above link, compile and use this .dll (inside bin/Debug subfolder) to your project .
Here is an example of what it looks like:
This looks like the simplest answer I have come across... just added an ItemCommand to the ListView.
See this link: handle-the-button-click-event-from-an-asp-net-listview-control
Related
I have a UWP project that uses MapControl, which is a sealed class - cant derive a new class from it.
Trying to make a bindable Attached Property, which would have access to MapControl.Children.
The problem is that it only works when I set ViewModel's collection, but not when I add a new element to that collection:
// Works fine
this.MapChildrenExtCollection = new ObservableCollection<MapChildElement>();
// Nothing happens
this.MapChildrenExtCollection.Add(new MapChildElement());
Heres my code for the Attached Property:
namespace UWPMap.Extensions
{
public class MapControlExt : DependencyObject
{
public static readonly DependencyProperty ChildrenExtProperty = DependencyProperty.Register(
"ChildrenExt",
typeof(ObservableCollection<MapChildElement>),
typeof(MapControlExt),
new PropertyMetadata(new ObservableCollection<MapChildElement>(), ChildrenExtPropertyChanged));
public ObservableCollection<MapChildElement> ChildrenExt
{
get { return (ObservableCollection<MapChildElement>)GetValue(ChildrenExtProperty); }
set { SetValue(ChildrenExtProperty, value); }
}
public static void SetChildrenExt(UIElement element, ObservableCollection<MapChildElement> value)
{
element.SetValue(ChildrenExtProperty, value);
}
public static ObservableCollection<MapChildElement> GetChildrenExt(UIElement element)
{
return (ObservableCollection<MapChildElement>)element.GetValue(ChildrenExtProperty);
}
private static void ChildrenExtPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var control = (MapControl)obj;
var oldCollection = e.OldValue as INotifyCollectionChanged;
var newCollection = e.NewValue as INotifyCollectionChanged;
if (oldCollection != null)
{
oldCollection.CollectionChanged -= Extensions.MapControlExt.ChildrenExtCollectionChanged;
}
if (newCollection != null)
{
oldCollection.CollectionChanged += Extensions.MapControlExt.ChildrenExtCollectionChanged;
}
ManageChildrenExt();
}
static void ChildrenExtCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
ManageChildrenExt();
}
static private void ManageChildrenExt()
{
// Access MapControl.Children here
}
}
}
XAML:
<maps:MapControl x:Name="MyMap"
ext:MapControlExt.ChildrenExt="{x:Bind Path=MapChildrenExtCollection, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
</maps:MapControl>
The problem is that you are not adding the event handler to the new collection and using oldCollection variable by mistake.
The following snippet:
if (newCollection != null)
{
oldCollection.CollectionChanged += //here you have oldCollection by mistake
Extensions.MapControlExt.ChildrenExtCollectionChanged;
}
Should be:
if (newCollection != null)
{
newCollection.CollectionChanged +=
Extensions.MapControlExt.ChildrenExtCollectionChanged;
}
I need to know, if the SelectedItems got filled when Ctrl or Shift was pressed or not. Is there an easy way (without creating a new controltemplate) to get this info? I prefer solutions without code behind.
Best regards
Yannik
You can wire up selection changed event, and check if Modifier Keys are pressed for Selection.
void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var isCtrlorShiftDown = (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl) || Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift));
if (isCtrlorShiftDown)
{
// Write your Logic Here;
}
}
I found a solution with minimal code behind.
The main concept is, that I attach to KeyDown and KeyUp events in the MainWindow and set a property "CurrentKeyboardKeyPressed" on the MainViewModel, which propagates the pressed key info to the child view models, which in turn fire a custom event with a special Selection class that has the currently pressed key info.
The posted source code is heavyli shortened and does not run at all. If somebody is interested in the working solution, just ask me and I will email it.
MainWindow.xaml.cs
public partial class MainWindow : Window
{
private readonly MainWindowViewModel _mainWindowViewModel;
public MainWindow()
{
_mainWindowViewModel = new MainWindowViewModel();
InitializeComponent();
DataContext = _mainWindowViewModel;
}
private void MainWindow_OnKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.LeftCtrl || e.Key == Key.RightCtrl)
{
_mainWindowViewModel.CurrentKeyboardKeyPressed = PressedKeyboardKey.Ctrl;
return;
}
if (e.Key == Key.LeftShift || e.Key == Key.RightShift)
{
_mainWindowViewModel.CurrentKeyboardKeyPressed = PressedKeyboardKey.Shift;
}
}
private void MainWindow_OnKeyUp(object sender, KeyEventArgs e)
{
_mainWindowViewModel.CurrentKeyboardKeyPressed = PressedKeyboardKey.None;
}
}
MainWindowViewModel.cs
public class MainWindowViewModel : ViewModelBase
{
// child view models
private readonly ObservableCollection<TTSViewModel> _ttsViewModels;
private PressedKeyboardKey _currentKeyboardKeyPressed;
public EventHandler<KeyboardKeyPressedEventArgs> CurrentKeyboardKeyPressedChanged;
public MainWindowViewModel()
{
_ttsViewModels = new ObservableCollection<TTSViewModel>();
}
public PressedKeyboardKey CurrentKeyboardKeyPressed
{
get { return _currentKeyboardKeyPressed; }
set
{
if (_currentKeyboardKeyPressed != value)
{
_currentKeyboardKeyPressed = value;
OnCurrentKeyboardKeyPressedChanged(_currentKeyboardKeyPressed);
}
}
}
// create child view models
public void PopulateTTSList(int itemsToCreated)
{
for (int i = 0; i < itemsToCreated; i++)
{
var tts = new TTSViewModel("TTS " + i);
tts.FractionSelectionChanged += OnTTSFractionSelectionChanged;
CurrentKeyboardKeyPressedChanged += tts.CurrentKeyboardKeyPressedChanged;
_ttsViewModels.Add(tts);
}
}
private void OnCurrentKeyboardKeyPressedChanged(PressedKeyboardKey currentKeyboardKeyPressed)
{
var handler = CurrentKeyboardKeyPressedChanged;
if (handler != null)
{
handler(this, new KeyboardKeyPressedEventArgs(currentKeyboardKeyPressed));
}
}
// selection changed handler for each child view model
private void OnTTSFractionSelectionChanged(object sender, ItemSelectionChangedEventArgs fractionSelectionChangedEventArgs)
{
var sendingTTS = sender as TTSViewModel;
if (fractionSelectionChangedEventArgs.Selection.PressedKeyOnSelection == PressedKeyboardKey.None)
{
// single selection action goes here
// ....
}
else
{
// multi selection action goes here
// ....
}
}
}
TTSViewModel.cs (child view model)
public class TTSViewModel : ViewModelBase
{
private readonly SmartObservableCollection<FractionViewModel> _currentlySelectedfractions;
public EventHandler<ItemSelectionChangedEventArgs> FractionSelectionChanged;
private PressedKeyboardKey _currentKeyboardKeyPressed;
public TTSViewModel()
{
_currentlySelectedfractions = new SmartObservableCollection<FractionViewModel>();
_currentlySelectedfractions.CollectionChanged += CurrentlySelectedfractionsOnCollectionChanged;
}
public void CurrentKeyboardKeyPressedChanged(object sender, KeyboardKeyPressedEventArgs currentKeyboardKeyPressedEventArgs)
{
_currentKeyboardKeyPressed = currentKeyboardKeyPressedEventArgs.CurrentKeyboardKeyPressed;
}
private void CurrentlySelectedfractionsOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs)
{
if (FractionSelectionChanged != null)
{
if (notifyCollectionChangedEventArgs.Action == NotifyCollectionChangedAction.Replace && notifyCollectionChangedEventArgs.NewItems != null)
{
var removed = _oldSelectedfractions.Except(_currentlySelectedfractions);
var added = _currentlySelectedfractions.Except(_oldSelectedfractions);
var selection = new Selection<FractionViewModel>(added, removed, _currentKeyboardKeyPressed);
_oldSelectedfractions.Clear();
foreach (var currentlySelectedfraction in _currentlySelectedfractions)
{
_oldSelectedfractions.Add(currentlySelectedfraction);
}
var selectionChangedArgs = new ItemSelectionChangedEventArgs(selection);
FractionSelectionChanged(this, selectionChangedArgs);
}
}
}
}
Selection.cs
public sealed class Selection<T>
{
private readonly List<T> _added;
private readonly List<T> _removed;
private readonly PressedKeyboardKey _currentKeyboardKeyPressed;
public Selection()
{
_added = new List<T>();
_removed = new List<T>();
}
/// <summary>
/// Initializes a new instance of the <see cref="Selection{T}" /> class.
/// </summary>
/// <param name="addedItems">[NotNull]</param>
/// <param name="removedItems">[NotNull]</param>
/// <param name="currentKeyboardKeyPressed">The current keyboard key pressed.</param>
public Selection(IEnumerable<T> addedItems, IEnumerable<T> removedItems, PressedKeyboardKey currentKeyboardKeyPressed)
: this()
{
_added.AddRange(addedItems);
_removed.AddRange(removedItems);
_currentKeyboardKeyPressed = currentKeyboardKeyPressed;
}
public IReadOnlyList<T> Added
{
get { return _added; }
}
public IReadOnlyList<T> Removed
{
get { return _removed; }
}
public PressedKeyboardKey PressedKeyOnSelection
{
get { return _currentKeyboardKeyPressed; }
}
}
KeyboardKeyPressedEventArgs.cs
public sealed class KeyboardKeyPressedEventArgs : EventArgs
{
public KeyboardKeyPressedEventArgs(PressedKeyboardKey currentKeyboardKeyPressed)
{
CurrentKeyboardKeyPressed = currentKeyboardKeyPressed;
}
public PressedKeyboardKey CurrentKeyboardKeyPressed { get; private set; }
}
ItemSelectionChangedEventArgs.cs
public sealed class ItemSelectionChangedEventArgs : EventArgs
{
public ItemSelectionChangedEventArgs(Selection<FractionViewModel> newSelection)
{
Selection = newSelection;
}
public Selection<FractionViewModel> Selection { get; private set; }
}
PressedKeyboardKey.cs
public enum PressedKeyboardKey
{
None,
Ctrl,
Shift
}
I have a simple problem. I am trying to add a dependency property to a combo box. I want to be able to display a value on the face of the combo box when it is initially displayed. There is a ContentPresenter with a TextBlock inside the ComboBox. That TextBlock gets set when a user selects an item in the ComboBox. How can I set that with a default value (not one of the items)? Show something like 'choose one'.
I can extend the ComboBox with a 'DefaultDisplay' dependency property but how do I 'link' that property to the TextBlock that is part of the control template?
Thanks for any help on this.
Pat
Instead of a dependency property I'd suggest using a behavior to do this. I actually already had one of these written for this problem. Give it a try by adding it to your combobox and setting the PromptText property on the behavior:
public class ComboBoxPromptBehavior : Behavior<ComboBox>
{
[Category("Display")]
public string PromptText
{
get { return (string)GetValue(PromptTextProperty); }
set { SetValue(PromptTextProperty, value); }
}
public static readonly DependencyProperty PromptTextProperty = DependencyProperty.Register("PromptText", typeof(string), typeof(ComboBoxPromptBehavior), new PropertyMetadata(" "));
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.Loaded += new RoutedEventHandler(AssociatedObject_Loaded);
AssociatedObject.LayoutUpdated += new EventHandler(AssociatedObject_LayoutUpdated);
}
void AssociatedObject_LayoutUpdated(object sender, EventArgs e)
{
SetPromptText();
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.Loaded -= new RoutedEventHandler(AssociatedObject_Loaded);
AssociatedObject.LayoutUpdated -= new EventHandler(AssociatedObject_LayoutUpdated);
}
void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
{
SetPromptText();
}
private void SetPromptText()
{
var textbox = AssociatedObject.FindChild<TextBlock>();
if (textbox != null && string.IsNullOrWhiteSpace(textbox.Text))
{
textbox.Text = PromptText;
}
}
}
And the extension method for FindChild is:
public static T FindChild<T>(this DependencyObject element) where T : DependencyObject
{
var childCount = VisualTreeHelper.GetChildrenCount(element);
for (int i = 0; i < childCount; i++)
{
var child = VisualTreeHelper.GetChild(element, i);
if (child is T)
{
return (T)child;
}
var match = child.FindChild<T>();
if (match != null) return match;
}
return null;
}
I've got an XNA + Silverlight game in Mango: Mostly XNA with some Silverlight UI on top. The problem I'm having is that when you hit a button or interact with a Silverlight control, the touch information is still passed along to the XNA game loop. How do you suppress this?
Wrote up a class to do the tracking for me. After your page loads (in the Loaded handler), create this and give it the root element (so it can attach to the LayoutUpdated event). Register any controls that might overlay the game surface during play. Then just call TouchesControl and pass in the touch position to find out if you should ignore that point or not. It caches the regions of the controls and updates them when there's a layout update.
Should work for rectangular elements moving, changing size or collapsing/expanding.
public class ControlTouchTracker
{
private List<FrameworkElement> controls = new List<FrameworkElement>();
private Dictionary<FrameworkElement, ControlRegion> controlBounds = new Dictionary<FrameworkElement, ControlRegion>();
public ControlTouchTracker(FrameworkElement rootElement)
{
rootElement.LayoutUpdated += this.OnLayoutUpdated;
}
public void RegisterControl(FrameworkElement control)
{
controls.Add(control);
}
public void RemoveControl(FrameworkElement control)
{
controls.Remove(control);
controlBounds.Remove(control);
}
private void OnLayoutUpdated(object sender, EventArgs e)
{
foreach (Control control in this.controls)
{
this.RefreshControlBounds(control);
}
}
private void RefreshControlBounds(FrameworkElement control)
{
if (this.ControlIsVisible(control))
{
try
{
GeneralTransform controlTransform = control.TransformToVisual(Application.Current.RootVisual);
Point offset = controlTransform.Transform(new Point(0, 0));
this.controlBounds[control] = new ControlRegion
{
Left = (float)offset.X,
Right = (float)(offset.X + control.ActualWidth),
Top = (float)offset.Y,
Bottom = (float)(offset.Y + control.ActualHeight)
};
}
catch (ArgumentException)
{
}
}
else
{
if (this.controlBounds.ContainsKey(control))
{
this.controlBounds.Remove(control);
}
}
}
private bool ControlIsVisible(FrameworkElement control)
{
// End case
if (control == null)
{
return true;
}
if (control.Visibility == Visibility.Collapsed)
{
return false;
}
return this.ControlIsVisible(control.Parent as FrameworkElement);
}
public bool TouchesControl(Vector2 touchPosition)
{
foreach (ControlRegion region in this.controlBounds.Values)
{
if (touchPosition.X >= region.Left && touchPosition.X <= region.Right &&
touchPosition.Y >= region.Top && touchPosition.Y <= region.Bottom)
{
return true;
}
}
return false;
}
public class ControlRegion
{
public float Left { get; set; }
public float Right { get; set; }
public float Top { get; set; }
public float Bottom { get; set; }
}
}
(edit) Updated example to work with parent elements changing Visibility.
Due to the way interop with XNA works, you will always get the touch input processed both by XNA and Silverlight - to some extent, XNA gets the priority, so the Silverlight acts on top of that. What you could do, if you need to ignore specific gesture locations (e.g. where Silverlight buttons are located), you could check the gesture position:
if (TouchPanel.IsGestureAvailable)
{
if (TouchPanel.ReadGesture().GestureType == GestureType.Tap)
{
if (TouchPanel.ReadGesture().Position == new Vector2(120, 120))
{
}
}
}
I have a WPF UI Bound to a collection of AwesomeClass
Now, AwesomeClass has a collection of AwesomeParts objects.
How can I make my UI In such a way that (as an example)
for each AwesomeClass instance, there is a Tab on a tab panel
and then for each awesome part in that, there is an object on a listbox, on that tab.
Basically: Awesomes->Tabs
And Then : Awesome.Awesomeparts->Tabs.Listbox
Following is the code to do what you are looking for :
public partial class TabWindow : Window
{
public TabWindow()
{
InitializeComponent();
List<AwesomeClass> items = new List<AwesomeClass>();
for (int i = 0; i < 10; i++)
{
items.Add(new AwesomeClass());
}
AwesomeTabs.ItemsSource = items;
Loaded += new RoutedEventHandler(TabWindow_Loaded);
}
// Method 1
void TabWindow_Loaded(object sender, RoutedEventArgs e)
{
FindListBox(AwesomeTabs);
}
private void FindListBox(DependencyObject obj)
{
Int32 count = VisualTreeHelper.GetChildrenCount(obj);
for (int i = 0; i < count; i++)
{
var child = VisualTreeHelper.GetChild(obj, i);
if (child is ListBox)
{
(child as ListBox).SelectionChanged += new SelectionChangedEventHandler(ListBox_SelectionChanged);
}
else
{
FindListBox(child);
}
}
}
// Method 2
private void ListBox_Loaded(object sender, RoutedEventArgs e)
{
(sender as ListBox).SelectionChanged += new SelectionChangedEventHandler(ListBox_SelectionChanged);
}
void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
MessageBox.Show(e.AddedItems[0].ToString());
}
catch (Exception)
{ }
}
}
class AwesomeClass
{
static Int32 count = 0;
public Int32 Index { get; set; }
public List<AwesomePart> Parts { get; protected set; }
// Method 3 : Preferred
private AwesomePart _selectedPart;
public AwesomePart SelectedPart
{
get { return _selectedPart; }
set
{
OnSelectionChanged(_selectedPart, value);
_selectedPart = value;
}
}
private void OnSelectionChanged(AwesomePart oldValue, AwesomePart newValue)
{
if (newValue != null) MessageBox.Show(newValue.ToString());
}
public AwesomeClass()
{
Index = ++count;
Parts = new List<AwesomePart>();
for (int i = 0; i < 10; i++)
{
Parts.Add(new AwesomePart());
}
}
public override string ToString()
{
return "Tab #" + Index.ToString();
}
}
class AwesomePart
{
static Int32 count = 0;
public Int32 Index { get; set; }
public AwesomePart()
{
Index = ++count;
}
public override string ToString()
{
return "Part #" + Index.ToString();
}
}
XAML:
<Grid>
<TabControl Name="AwesomeTabs">
<TabControl.ContentTemplate>
<DataTemplate>
<ListBox ItemsSource="{Binding Parts}" SelectedItem="{Binding SelectedPart}" Loaded="ListBox_Loaded"></ListBox>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
</Grid>
Bind a List<AwesomeClass> to a headered content control. Each "AwesomeClass" object will be set as the datacontext for each "tab" in the headered content control.
Within the content control that is on each "tab", bind the DataContext (AwesomeClass) property that accesses the List<AwesomePart> to your Listbox control.
Make sense?
Cheers.