Select all check boxes WPF - c#

I want to make all check boxes selected by selecting check box names with "All of Above".
the checkboxes are in a List box
<ListBox SelectionMode="Multiple"
BorderThickness="0"
ItemsSource="{Binding QuestionThreeSelection}"
SelectedItem="{Binding QuestionThreeSelection}"
Name="listBoxList"
SelectionChanged="listBoxList_SelectionChanged">
<ListBox.InputBindings>
<KeyBinding Command="ApplicationCommands.SelectAll"
Modifiers="Ctrl"
Key="A" />
</ListBox.InputBindings>
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Checked="CheckBox_Checked_1"
Content="{Binding SourceName}"
IsChecked="{Binding Path=IsSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
back Code
private void CheckBox_Checked_1(object sender, RoutedEventArgs e)
{
var oo = listBoxList;
CheckBox cb = (CheckBox)sender;
//var w=e;
IEnumerable<AddSource> listallityem = ((IEnumerable<AddSource>)listBoxList.Items.SourceCollection).Where(r => r.IsSelected == false);
//IEnumerable<AddSource> listallityem1 = ((IEnumerable<AddSource>)listBoxList.Items.SourceCollection);
AddSource vv = cb.DataContext as AddSource;
if ((bool) cb.IsChecked)
{
}
if (vv.SourceName== "All of the above")
{
r = listBoxList.ItemsSource;
foreach (AddSource item in wer)
{
item.IsSelected = true; // false in case of unselect
}
}
}
Can someone suggest a method?

You could handle the Checked and Unchecked event for your "All of Above" CheckBox something like this:
private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
SelectAll(true);
}
private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
{
SelectAll(false);
}
private void SelectAll(bool select)
{
var all = listBoxList.ItemsSource as IEnumerable<AddSource>;
if (all != null)
{
foreach (var source in all)
source.IsSelected = select;
}
}
Make sure that your AddSource class implements the INotifyPropertyChanged and raise the PropertyChanged event in the setter of the IsSelected property.

Related

How to change the editable ComboBox's text to something else when a specific ComboBoxItem is selected?

The new text will never be present in the items inside ComboBox. Below is the full XAML + code-behind that does not work as I wish. What I am trying to achieve is to have the user select an actual group of items from the combo box, or a No Group (italic, grayed out) item that should be applied as an empty string in the text box inside the ComboBox.
I also tried:
with StaysOpenOnEdit="True" (with the same result) and
by handling the Selected event of the "click me" ComboBoxItem (the event handler is called before the Text or SelectedItem properties of the ComboBox change).
XAML
<Window x:Class="cs_wpf_test_12.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:cs_wpf_test_12"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<StackPanel Orientation="Vertical">
<ComboBox SelectionChanged="ComboBox_SelectionChanged"
IsEditable="True">
<ComboBoxItem>test</ComboBoxItem>
<ComboBoxItem Foreground="Gray">click me</ComboBoxItem>
</ComboBox>
</StackPanel>
</Window>
Code-behind
internal bool HandlingSelectionChange = false;
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (HandlingSelectionChange)
{
return;
}
HandlingSelectionChange = true;
var cb = sender as ComboBox;
if (cb.Text == "click me")
{
cb.Text = "";
e.Handled = true;
}
HandlingSelectionChange = false;
}
Expected: when the user clicks on the "click me" item in the drop-down the text of the ComboBox becomes an empty string. The rest of the items, when clicked, should copy their text normally into the text box of the ComboBox.
Actual:
Start the program.
Select the "click me" item.
The Text changes to "click me" (not grayed out) instead of "".
Click on the "test" item.
The Text changes to "" (empty string) instead of "test".
Click again on the "test" item.
The Text changes to "test".
Update
I wish to use MVVM but I am still a beginner. I have several ComboBoxes like shown above inside a DataGridTemplateColumn, and for each of the ComboBoxes (which should have the same drop-down contents) I think I should have a ViewModel for each of its ComboBoxItems. If possible, I would like to learn how I could I use MVVM correctly in this situation.
The big XAML
<DataGridTemplateColumn Header="Group Name">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Label Content="{Binding GroupName, Mode=OneWay}">
</Label>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox IsEditable="True" StaysOpenOnEdit="True"
ItemsSource="{Binding Path=Clocks.GroupsVM,
RelativeSource={RelativeSource AncestorType=local:ClockDataGrid}}"
PreviewKeyDown="ComboBox_PreviewKeyDown"
SelectionChanged="ComboBox_SelectionChanged"
Text="{Binding GroupName}">
<ComboBox.Resources>
<Style TargetType="ComboBoxItem">
<Setter Property="FontStyle" Value="{Binding FontStyle}"/>
<Setter Property="Foreground" Value="{Binding Foreground}"/>
</Style>
</ComboBox.Resources>
</ComboBox>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
The big code-behind
private void ComboBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
var cb = sender as ComboBox;
if ((e.Key == Key.Return ||
e.Key == Key.Enter) &&
cb.Text != "")
{
bool duplicate = false;
foreach (ClockGroupVM vm in Clocks.GroupsVM)
{
if (vm.Name == cb.Text)
{
cb.SelectedItem = vm;
duplicate = true;
break;
}
}
if (duplicate)
{
return;
}
// create a ClockGroupM and corresponding ClockGroupVM
// (ClockGroupVM inherits from ClockGroupM)
var cvm = new ClockGroupVM()
{
Name = cb.Text
};
Clocks.Groups.Insert(0, cvm);
cb.SelectedItem = cvm;
}
}
internal bool HandlingSelectionChange = false;
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (HandlingSelectionChange)
{
return;
}
HandlingSelectionChange = true;
var cb = sender as ComboBox;
//if (cb.SelectedItem is the VM with Style != Normal)
ClockGroupVM foundVM = null;
foreach (ClockGroupVM vm in Clocks.GroupsVM)
{
if (vm.FontStyle != FontStyles.Normal &&
ReferenceEquals(cb.SelectedItem, vm))
{
foundVM = vm;
break;
}
}
if (foundVM != null)
{
cb.Text = "";
e.Handled = true;
}
HandlingSelectionChange = false;
}
ComboBox.Text wont update immediately in the SelectionChanged event. You can use SelectedValue's content instead. And set SelectedValue to null. Change your if condition like this.
if ((cb.SelectedValue as ComboBoxItem).Content.ToString() == "click me")
{
cb.Text = "";
cb.SelectedValue = null;
e.Handled = true;
}

TextBox doesn't accept dragging files from Explorer

I have a simple TextBox control inside a complex UserControl
where I'd like to drop files from Windows Explorer.
Here is the XAML code:
<TextBox x:Name="txtMessage"
AcceptsReturn="True"
AcceptsTab="True"
AllowDrop="True"
PreviewDragOver="TxtMessage_OnDragEnter"
PreviewDragEnter="TxtMessage_OnDragEnter"
PreviewDrop="TxtMessage_OnDrop"
IsEnabled="{Binding IsMessageFieldEnabled}"
Text="{Binding Message, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
FontSize="14">
<TextBox.InputBindings>
<KeyBinding Key="Enter"
Command="{Binding CommandSendMessage}">
</KeyBinding>
</TextBox.InputBindings>
</TextBox>
and here is the code behind:
private void TxtMessage_OnDrop(object sender, DragEventArgs e)
{
IDragAndDrop dd = DataContext as IDragAndDrop;
if (dd == null)
{
return;
}
dd.TryDrop(e.Data);
e.Handled = true;
}
private void TxtMessage_OnDragEnter(object sender, DragEventArgs e)
{
IDragAndDrop dd = DataContext as IDragAndDrop;
if (dd == null)
{
e.Effects = DragDropEffects.None;
return;
}
e.Effects = dd.CheckForAllowedDragDrop(e.Data);
e.Handled = true;
}
The problem is that my code behind is not called at all. Why this might happen? What would prohibit drag & drop stuff to work on a certain control?

How to extract value from selected TextBlock element in a ListBox?

I'm using a ListBox to display all values contained in Dictionary<> object:
<ListBox Height="519" x:Name="ContactsListBox" Width="460" Margin="0,0,0,0" SelectionChanged="ContactsListBox_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Key}" Margin="5" Foreground="{StaticResource PhoneAccentBrush}"/>
<TextBlock x:Name ="LastNameData" Text="{Binding Value}" Margin="20, 0" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Content is filled by the following code:
Dictionary<long, Contact> contacts = new Dictionary<long, Contact>();
this.ContactsListBox.ItemsSource = contacts;
Now, I would like to 'know' which specific "Contact" in ListBox is currently selected, either by knowing its Key, or just by extracting value from "LastNameData" TextBlock.
I tried doing something like that, but obviosly it doesn't work:
private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBox lb = this.ContactsListBox.SelectedItem as ListBox;
this.Test_SomeOtherTextBlock.Text = lb.ToString();
}
I would really appreciate your help!
you can even do the follwing:
<ListBox Height="519" x:Name="ContactsListBox" Width="460" Margin="0,0,0,0" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Key}" Margin="5"/>
<TextBlock x:Name ="LastNameData" Text="{Binding Value}" Margin="20, 0" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Grid DataContext="{Binding ElementName=ContactsListBox, Path=SelectedItem}" Margin="0,470,0,0">
<TextBlock Text="{Binding Value}"/>
</Grid>
So you don't need code behind...
BR,
TJ
There are several problems:
In Xaml you probably don't want to display the class name, but a reasonable string, for example:
<TextBlock x:Name ="LastNameData" Text="{Binding Value.LastName}" Margin="20, 0" />
In the selection processing the selected item is KeyValuePair<...>. You could easily find it yourself, if you looked at the returned type in debugger. (Should be kind of a reflex for a programmer, hence a questions like above should never appear :))
private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) {
KeyValuePair<long, Contact> kv = (KeyValuePair<long, Contact>)this.ContactsListBox.SelectedItem;
Contact c = (Contact)kv.Value;
Debug.WriteLine(c.LastName);
}
Your code is good, using ListBox.SelectedItem is the right approach.
I think the problem is that you should cast it as ListBoxItem, not ListBox. And also to get to its value using DataContext, so something like along these lines (not tested, I'm not sure about accessing DataContext value in the last line):
private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBoxItem lbi = this.ContactsListBox.SelectedItem as ListBoxItem;
var dataContext = lbi.DataContext;
this.Test_SomeOtherTextBlock.Text = dataContext.Value.ToString();
}
Try this it works for me, will help you to...
private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBox ContactListBox = sender as ListBox;
ListBoxItem listBoxItem = ContactListBox .ItemContainerGenerator.ContainerFromItem(ContactListBox.SelectedItem) as ListBoxItem;
if (listBoxItem == null)
{
return;
}
TextBlock txtBlock = FindVisualChildByName(listBoxItem, "ListTextBlock");
MessageBox.Show(txtBlock.Text);
}
private static T FindVisualChildByName<T>(DependencyObject parent, string name) where T : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
string controlName = child.GetValue(NameProperty) as string;
if (controlName == name)
{
return child as T;
}
T result = FindVisualChildByName<T>(child, name);
if (result != null)
return result;
}
return null;
}
private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBox lb = this.ContactsListBox.SelectedItem as ListBox;
this.Test_SomeOtherTextBlock.Text = lb.ToString();
}
will go something like this..
private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBox lb = this.ContactsListBox.SelectedItem as ListBox;
DataTemplate template=lb.ContentTemplate;
//Now here you have to extract the content of the data template
and then you need to extract the TextBlock from that content.
}
This is just an overview of the functionality.Sorry not able to post complete code.

How do I know that a Silverlight control has been displayed?

I have a list box displaying the names of help topics which can be added to and the names of the topics changed. Originally it was just displaying strings, but to get the inline editing working I changed it to use a custom type consisting of a string and an InEdit property so the UI can determine whether to display the TextBlock or TextBox:
XAML:
<ListBox ItemsSource="{Binding HelpTopics, Mode=TwoWay}"
SelectedValuePath="Description"
SelectedValue="{Binding SelectedPageId, Mode=TwoWay}"
SelectionChanged="ListBox_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding Description, Mode=TwoWay}"
VerticalAlignment="Center"
MouseLeftButtonUp="TopicTextBlock_MouseLeftButtonUp"
Visibility="{Binding InEdit, Converter={StaticResource boolToVisibilityConverter}, ConverterParameter=contra}"/>
<TextBox Text="{Binding Description, Mode=TwoWay}"
Visibility="{Binding InEdit, Converter={StaticResource boolToVisibilityConverter}, ConverterParameter=pro}"
LostFocus="EditTopicTextBox_LostFocus"
HorizontalAlignment="Stretch" VerticalAlignment="Center"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button Margin="5" Content="Add Topic" Command="{Binding AddTopicCommand}"/>
HelpTopics is an ObservableCollection<EditableHelpTopic>.
SelectedPageId is a string.
boolToVisibilityConverter is a converter that does what it says.
What works:
Adding a topic creates a new item and adds it to the list and put the item in to edit mode.
Double clicking on an existing item puts that item into edit mode sets the focus to the TextBox and selects all the text so it can be overwritten.
When the TextBox loses focus the edit is saved and the display returns to the TextBlock.
What doesn't work:
When a new topic is added the TextBox should have focus and the text selected so the user can enter a new name.
So my question is is there a point in the code or an event where I know that the TextBox has been created and is visible so I can set focus and select its contents. I've tried hooking into the SelectionChanged event but when that fires the TextBox hasn't yet been displayed. I also added an event to the OnAddTopicExecute method in the view model which I handled in the view, but again that fired before the TextBox was visible.
Below is the code that supports the above XAML. I've tried to cut it down, but there still seems to be a lot of it, so you can skip this if you're not interested ;)
Code behind:
private DateTime lastClickTime = DateTime.MinValue;
private Point lastClickPosition;
private void TopicTextBlock_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
UIElement element = sender as UIElement;
if ((DateTime.Now - this.lastClickTime).TotalMilliseconds > 300)
{
this.lastClickPosition = e.GetPosition(element);
this.lastClickTime = DateTime.Now;
}
else
{
Point position = e.GetPosition(element);
if (Math.Abs(this.lastClickPosition.X - position.X) < 4 && Math.Abs(this.lastClickPosition.Y - position.Y) < 4)
{
var textBlock = sender as TextBlock;
var editableHelpTopic = textBlock.DataContext as EditableHelpTopic;
editableHelpTopic.InEdit = true;
var parent = textBlock.Parent as Grid;
TextBox textBox = parent.Children.First(c => c.GetType() == typeof(TextBox)) as TextBox;
textBox.Focus();
textBox.SelectAll();
}
}
}
private void EditTopicTextBox_LostFocus(object sender, RoutedEventArgs e)
{
var textBox = sender as TextBox;
var editableHelpTopic = textBox.DataContext as EditableHelpTopic;
editableHelpTopic.InEdit = false;
if (!textBox.Text.Equals(editableHelpTopic.Description))
{
this.editViewModel.RenameTopic(textBox.Text);
}
}
View Model:
public EditViewModel()
{
...
this.AddTopicCommand = new DelegateCommand(this.OnAddTopicExecute, this.OnAddTopicCanExecute);
...
}
where DelegateCommand is an implemetation of ICommand.
private void OnAddTopicExecute(object parameter)
{
var newTopic = new EditableHelpTopic
{
Description = "NewTopic",
InEdit = true
};
this.HelpTopics.Add(newTopic);
this.SelectedPageId = newTopic.Description;
}
Definitions:
public class EditableHelpTopic : INotifyPropertyChanged
{
public bool InEdit { ... }
public string Description { ... }
}
It turned out to be simpler than I thought.
I just needed to add a Loaded event handler to the TextBox:
private void EditTopicTextBox_Loaded(object sender, RoutedEventArgs e)
{
var textBox = sender as TextBox;
var editableHelpTopic = textBox.DataContext as EditableHelpTopic;
if (editableHelpTopic.InEdit)
{
textBox.Focus();
textBox.SelectAll();
}
}

Get the item doubleclick event of listview

What do I need to do in order to reference the double click event for a listview control?
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<EventSetter Event="MouseDoubleClick" Handler="listViewItem_MouseDoubleClick" />
</Style>
</ListView.ItemContainerStyle>
The only difficulty then is if you are interested in the underlying object the listviewitem maps to e.g.
private void listViewItem_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
ListViewItem item = sender as ListViewItem;
object obj = item.Content;
}
I'm using something like this to only trigger on ListViewItem double-click and not for example when you double-click on the header of the ListView.
private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
DependencyObject obj = (DependencyObject)e.OriginalSource;
while (obj != null && obj != myListView)
{
if (obj.GetType() == typeof(ListViewItem))
{
// Do something here
MessageBox.Show("A ListViewItem was double clicked!");
break;
}
obj = VisualTreeHelper.GetParent(obj);
}
}
Use the ListView.HitTest method
private void listView_MouseDoubleClick(object sender, MouseEventArgs e)
{
var senderList = (ListView) sender;
var clickedItem = senderList.HitTest(e.Location).Item;
if (clickedItem != null)
{
//do something
}
}
Or the old way
private void listView_MouseDoubleClick(object sender, MouseEventArgs e)
{
var senderList = (ListView) sender;
if (senderList.SelectedItems.Count == 1 && IsInBound(e.Location, senderList.SelectedItems[0].Bounds))
{
//Do something
}
}
public bool IsInBound(Point location, Rectangle bound)
{
return (bound.Y <= location.Y &&
bound.Y + bound.Height >= location.Y &&
bound.X <= location.X &&
bound.X + bound.Width >= location.X);
}
private void positionsListView_DoubleClick(object sender, EventArgs e)
{
if (positionsListView.SelectedItems.Count == 1)
{
ListView.SelectedListViewItemCollection items = positionsListView.SelectedItems;
ListViewItem lvItem = items[0];
string what = lvItem.Text;
}
}
I don't yet have a large enough reputation score to add a comment where it would be most helpful, but this is in relation to those asking about a .Net 4.5 solution.
You can use the mouse X and Y co-ordinates and the ListView method GetItemAt to find the item which has been clicked on.
private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
ListViewItem item = myListView.GetItemAt(e.X, e.Y)
// Do something here
}
I needed that as well. I found that on msdn:
http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.activation.aspx
I think this delegate is for that.
for me, I do double click of ListView in this code section .
this.listView.Activation = ItemActivation.TwoClick;
this.listView.ItemActivate += ListView1_ItemActivate;
ItemActivate specify how user activate with items
When user do double click, ListView1_ItemActivate will be trigger.
Property of ListView ItemActivate refers to access the collection of items selected.
private void ListView1_ItemActivate(Object sender, EventArgs e)
{
foreach (ListViewItem item in listView.SelectedItems)
//do something
}
it works for me.
I found this on Microsoft Dev Center. It works correctly and ignores double-clicking in wrong places. As you see, the point is that an item gets selected before double-click event is triggered.
private void listView1_DoubleClick(object sender, EventArgs e)
{
// user clicked an item of listview control
if (listView1.SelectedItems.Count == 1)
{
//do what you need to do here
}
}
http://social.msdn.microsoft.com/forums/en-US/winforms/thread/588b1053-8a8f-44ab-8b44-2e42062fb663
Here is how to get the selected object and object matching code for the double clicked listview item in a WPF listview:
/// <summary>
/// Get the object from the selected listview item.
/// </summary>
/// <param name="LV"></param>
/// <param name="originalSource"></param>
/// <returns></returns>
private object GetListViewItemObject(ListView LV, object originalSource)
{
DependencyObject dep = (DependencyObject)originalSource;
while ((dep != null) && !(dep.GetType() == typeof(ListViewItem)))
{
dep = VisualTreeHelper.GetParent(dep);
}
if (dep == null)
return null;
object obj = (Object)LV.ItemContainerGenerator.ItemFromContainer(dep);
return obj;
}
private void lvFiles_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
object obj = GetListViewItemObject(lvFiles, e.OriginalSource);
if (obj.GetType() == typeof(MyObject))
{
MyObject MyObject = (MyObject)obj;
// Add the rest of your logic here.
}
}
You can get the ListView first, and then get the Selected ListViewItem.
I have an example for ListBox, but ListView should be similar.
private void listBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
ListBox box = sender as ListBox;
if (box == null) {
return;
}
MyInfo info = box.SelectedItem as MyInfo;
if (info == null)
return;
/* your code here */
}
e.Handled = true;
}
Either use the MouseDoubleClick event, and also, all the MouseClick events have a click count in the eventargs variable 'e'. So if e.ClickCount == 2, then doubleclicked.
In the ListBox DoubleClick event get the selecteditem(s) member of the listbox, and there you are.
void ListBox1DoubleClick(object sender, EventArgs e)
{
MessageBox.Show(string.Format("SelectedItem:\n{0}",listBox1.SelectedItem.ToString()));
}
It's annoying, but the best way to do it is something like:
<DataTemplate Name="MyCoolDataTemplate">
<Grid Loaded="HookLVIClicked" Tag="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListViewItem}}}">
<!-- your code here -->
</Grid>
</DataTemplate>
Then in the code:
public void HookLVIClicked(object sender, RoutedEventArgs e) {
var fe = (FrameworkElement)sender;
var lvi = (ListViewItem)fe.Tag;
lvi.MouseDoubleClick += MyMouseDoubleClickHandler;
}
Was having a similar issue with a ListBox wanting to open a window (Different View) with the SelectedItem as the context (in my case, so I can edit it).
The three options I've found are: 1. Code Behind 2. Using Attached Behaviors 3. Using Blend's i:Interaction and EventToCommand using MVVM-Light.
I went with the 3rd option, and it looks something along these lines:
<ListBox x:Name="You_Need_This_Name"
ItemsSource="{Binding Your_Collection_Name_Here}"
SelectedItem="{Binding Your_Property_Name_Here, UpdateSourceTrigger=PropertyChanged}"
... rest of your needed stuff here ...
>
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
<Command:EventToCommand Command="{Binding Your_Command_Name_Here}"
CommandParameter="{Binding ElementName=You_Need_This_Name,Path=SelectedItem}" />
</i:EventTrigger>
</i:Interaction.Triggers>
That's about it ... when you double click on the item you want, your method on the ViewModel will be called with the SelectedItem as parameter, and you can do whatever you want there :)
The sender is of type ListView not ListViewItem.
private void listViewTriggers_MouseDoubleClick(object sender, MouseEventArgs e)
{
ListView triggerView = sender as ListView;
if (triggerView != null)
{
btnEditTrigger_Click(null, null);
}
}
i see this subject is high on google, there is my simple and working sample :)
XAML:
<ListView Name="MainTCList" HorizontalAlignment="Stretch" MinHeight="440" Height="Auto" Margin="10,10,5.115,4" VerticalAlignment="Stretch" MinWidth="500" Width="Auto" Grid.Column="0" MouseDoubleClick="MainTCList_MouseDoubleClick" IsSynchronizedWithCurrentItem="True">
<ListView.View>
<GridView>
<GridViewColumn Header="UserTID" DisplayMemberBinding="{Binding UserTID}" Width="80"/>
<GridViewColumn Header="Title" DisplayMemberBinding="{Binding Title}" Width="410" />
</GridView>
</ListView.View>
</ListView>
C#
private void MainTCList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
TC item = (TC)MainTCList.Items.CurrentItem;
Wyswietlacz.Content = item.UserTID;
}
Wyswietlacz is a test Label to see item content :) I add here in this last line a method to Load Page with data from item.

Categories

Resources