Create contextmenus for datagrid rows - wpf

I have a datagrid that potentially can have many rows. As the user right clicks one of the rows, I need to show a context menu for each of the rows and perform an action (same action but different data item according to the current selected row) when the user clicks the option.
What is the best strategy for this?
I'm fearing that a ContextMenu for each row is overkill even though I'm creating the menu using the ContextMenuOpening event, sort of a "lazy load" for the context menu. Should I only use one ContextMenu for the datagrid? But with this I would have some more work regarding the click event, to determine the correct row, etc.

As far as I know, some of the actions will be disabled or enabled depending on the row, so there is no point in a single ContextMenu for a DataGrid.
I have an example of the row-level context menu.
<UserControl.Resources>
<ContextMenu x:Key="RowMenu" DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}">
<MenuItem Header="Edit" Command="{Binding EditCommand}"/>
</ContextMenu>
<Style x:Key="DefaultRowStyle" TargetType="{x:Type DataGridRow}">
<Setter Property="ContextMenu" Value="{StaticResource RowMenu}" />
</Style>
</UserControl.Resources>
<DataGrid RowStyle="{StaticResource DefaultRowStyle}"/>
The DataGrid must have a binding to a list of view models with commands:
public class ItemModel
{
public ItemModel()
{
this.EditCommand = new SimpleCommand
{
ExecuteDelegate = _ => MessageBox.Show("Execute"),
CanExecuteDelegate = _ => this.Id == 1
};
}
public int Id { get; set; }
public string Title { get; set; }
public ICommand EditCommand { get; set; }
}
The context menu is created in the resources collection of the UserControl and I think there is only one object which is connected with datagrid rows by reference, not by value.
Here is another example of ContextMenu for a Command inside a MainViewModel. I suppose that DataGrid has a correct view model as the DataContext, also the CommandParameter attribute must be placed before the Command attribute:
<ContextMenu x:Key="RowMenu" DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}">
<MenuItem Header="Edit" CommandParameter="{Binding}"
Command="{Binding DataContext.DataGridActionCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGrid}}" />
</ContextMenu>
Models:
public class MainViewModel
{
public MainViewModel()
{
this.DataGridActionCommand = new DelegateCommand<ItemModel>(m => MessageBox.Show(m.Title), m => m != null && m.Id != 2);
}
public DelegateCommand<ItemModel> DataGridActionCommand { get; set; }
public List<ItemModel> Items { get; set; }
}
public class ItemModel
{
public int Id { get; set; }
public string Title { get; set; }
}
But there is a problem that MenuItem isn't displayed as a disabled item if CanExecute returns false. The possible workaround is using a ParentModel property inside the ItemModel, but it doesn't differ much from the first solution.
Here is example of above-described solution:
public class ItemModel
{
public int Id { get; set; }
public string Title { get; set; }
public MainViewModel ParentViewModel { get; set; }
}
//Somewhere in the code-behind, create the main view model
//and force child items to use this model as a parent model
var mainModel = new MainViewModel { Items = items.Select(item => new ItemViewModel(item, mainModel)).ToList()};
And MenuItem in XAML will be simplier:
<MenuItem Header="Edit" CommandParameter="{Binding}"
Command="{Binding ParentViewModel.DataGridActionCommand}" />

Related

Double Click event is not working on ListBox using MVVM in WPF app

I am facing a problem while binding the double click event on Listbox item.
I am using MVVM and Prism. I didn't understand what is wrong here.
View
<ListBox HorizontalAlignment="Center" ItemsSource="{Binding Cities , Source={StaticResource vmC}}" SelectedItem="{Binding SelectedCity , Source={StaticResource vmC}}" Width="100" Height="200">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}">
<TextBlock.InputBindings>
<MouseBinding Gesture="LeftDoubleClick"
Command="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=DataContext.ItemSelectedCommand}"/>
</TextBlock.InputBindings>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
ViewModel
public class CityViewModel : ViewModelBase
{
public DelegateCommand ItemSelectedCommand { get; private set; }
public string SelectedCity { get; set; }
public List<string> Cities { get; private set; }
public CityViewModel()
{
ItemSelectedCommand = new DelegateCommand(OnItemSelected);
Cities = new List<string>() { "Bangalore", "New York", "Sydney", "London", "Washington" };
}
private void OnItemSelected()
{
var city = SelectedCity;
}
}
MouseBinding is not part of the visual tree. This means, you cannot use Binding.RelativeSource as there is no tree to traverse.
Instead you must bind to the current DataContext, which is the item's data model. To accomplish this, you would have tzo introduce a model class e.g. City that exposes a Name and ItemSelectedCommand property.
If moving the command to the item model doesn't make sense in your scenario, you should use a RoutedCommand and handle it e.g., in the parent Window. InputBinding is primarily intended to be used in the view only and therefore encourages the use of RoutedCommand.
In your case, it seems you are only interested in notifying the CityViewModel that the selection has changed. In this case simply call OnItemSelected from the SelectedCity property set():
public class CityViewModel : ViewModelBase
{
private string selectedCity;
public string SelectedCity
{
get => selectedCity;
set
{
selectedCity = value;
OnItemSelected();
}
}
public List<string> Cities { get; private set; }
public CityViewModel()
{
...
}
private void OnItemSelected()
{
var city = SelectedCity;
}
}

Calling a command from item collection in PRISM/ MEF/ WPF

Suppose I have the following:
<Grid x:Name="root">
<ListBox ItemsSource="{Binding Path=Items}">
<ListBox.ItemTemplate>
<DataTemplate>
<DockPanel>
<Button Command="{Binding ElementName=root, Path=DataContext.MyCommand}" />
<!---There are other UI elements here -->
</DockPanel/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
This code executes MyCommand when the button is clicked, but I also want to execute MyCommand when the user presses Enter Key while the row is selected (which means button is not in focus)...
How to best do this in WPF/MEF/PRISM?
I recognize that in code I can't cast the DataContext to (MyViewModel) because that would violate MEF, and in code behind I only know the viewmodel interface type IViewModel...
//code behind of the XAML file above
public IViewModel ViewModel
{
get;
set;
}
Note: I am thinking of doing this in code behind, but I'm not sure if the answer is even I should do it in the viewmodel...
This can be done using KeyBindings. Create a new KeyBidnign to your Window and associate a Command to it. More information on KeyBindings.
<ListBox.InputBindings>
<KeyBinding Key="Enter" Command="{Binding MyCommand}"/>
</ListBox.InputBindings>
The CanExecute method of your viewmodel should have a validation for Selected Row.
public class ViewModel
{
public ViewModel()
{
MyCommand = new DelegateCommand(MyCommandExecute, MyCommandCanExecute);
}
private void MyCommandExecute()
{
// Do your logic
}
private bool MyCommandCanExecute()
{
return this.SelectedRow != null;
}
public object SelectedRow { get; set; }
public DelegateCommand MyCommand { get; set; }
}

Context menu commands in an Observable Collection

I am new to WPF and am trying to bind a context menu to an ObservableCollection of models. I am able to get the context menu to display but I can't get the commands to fire. Here is my code
<ContextMenu ItemsSource="{Binding ContextMenuList}">
<ContextMenu.ItemContainerStyle>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="MenuItem.Header" Value="{Binding Name}" />
<Setter Property="MenuItem.ItemsSource" Value ="{Binding Children}" />
<Setter Property="Command" Value="{Binding MenuCommand}"/>
</Style>
</ContextMenu.ItemContainerStyle>
</ContextMenu>
In the View Model I have
public class MenuItemViewModel
{
public string Name { get; set; }
public ObservableCollection Children { get; set; }
public ICommand MenuCommand;
public MenuItemViewModel(string name, ObservableCollection pChildren, ICommand pCommand)
{
this.Name = name;
this.Children = pChildren;
this.MenuCommand = pCommand;
}
}
and I populate the collection
public void AddContextMenuItems()
{
this.ContextMenuList = new ObservableCollection<MenuItemViewModel>();
ICommand pCommand = new ActionCommand(() => this.ChangeChartType());
MenuItemViewModel ohlc = new MenuItemViewModel("OHLC",null,pCommand);
MenuItemViewModel candlestick = new MenuItemViewModel("CandleStick");
ObservableCollection<MenuItemViewModel> chartTypeColl = new ObservableCollection<MenuItemViewModel>();
chartTypeColl.Add(ohlc);
chartTypeColl.Add(candlestick);
this.ContextMenuList.Add(new MenuItemViewModel("ChartType",chartTypeColl));
}
I don't see the ChangeChartType method ever get triggered, what I am I doing wrong here ?
Try to change MenuCommand field to property
public ICommand MenuCommand { get; set; }
Hope this work for you. I haven't tried this though.

ContextMenu bound to ObservableCollection<MenuItem> does not refresh data

Given the following XAML snippet:
<UserControl.Resources>
<ResourceDictionary>
<Style x:Key="ContextMenuItemStyle">
<Setter Property="MenuItem.Header" Value="{Binding Text}"/>
<Setter Property="MenuItem.ItemsSource" Value="{Binding Children}"/>
<Setter Property="MenuItem.Command" Value="{Binding Command}" />
</Style>
<ContextMenu x:Key="contextMenu" ItemsSource="{Binding MenuOptions}" ItemContainerStyle="{StaticResource ContextMenuItemStyle}" />
</ResourceDictionary>
</UserControl.Resources>
<DockPanel>
<TextBox Height="30" DockPanel.Dock="Top" ContextMenu="{StaticResource contextMenu}" />
<Button Content="Add Menu Item" DockPanel.Dock="Top" Command="{Binding AddMenuItem}" />
</DockPanel>
And View Model:
public class MyViewModel {
public ObservableCollection<MenuItem> DocumentExplorerMenuOptions { get; set; }
MenuItem firstMenuItem;
MenuItem secondMenuItem;
public MyViewModel() {
firstMenuItem = new MenuItem("First") { Command = new DelegatingCommand(x => MessageBox.Show("First Selected") };
secondMenuItem = new MenuItem("Second") { Command = new DelegatingCommand(x => MessageBox.Show("Second Selected") };
MenuOptions = new ObservableCollection<MenuItem> { firstMenuItem, secondMenuItem };
AddMenuItem = new DelegateCommand<object>(x => firstMenuItem.Children.Add(
new MenuItem("Child of First")));
}
public DelegateCommand<object> AddMenuItem { get; set; }
}
And class:
public class MenuItem {
public MenuItem(string text) {
Text = text;
Children = new List<MenuItem>();
}
public string Text { get; set; }
public List<MenuItem> Children { get; private set; }
public ICommand Command { get; set; }
}
Clicking the button does add the child to firstMenuItem but it does not appear in the context menu of the TextBox.
I can't figure out how to make the context menu show the dynamic content of the context menu. Any thoughts?
I would not bind to a collection of MenuItems but rather to a more data-driven collection which may contain the MenuItem header, a command which is executed upon click and another collection of such items for the sub-items. Then you could use a (Hierarchical)DataTemplate to generate the menu on the fly. Doing so would probably take care of update issues if your datatype implements the necessary interfaces.
Edit: You seem to have such a datatype already, could you post its code?
Edit2: I think the problem is that you use a style that explicitly needs to be applied (it is probably only being applied to the main context menu, not the sub-items), as noted before i'd suggest a HierarchicalDataTemplate.
Edit3: lol...
public List<MenuItem> Children { get; private set; }
Of course it's not going to update if it's a List and not an ObservableCollection.
(The class is quite badly designed overall by the way, Lists should normally not even have a private setter, they should be properties with just a getter to a readonly field)

Child item in TreeView not updating

I copied the basic method of having checkbox in a treeview from the official Silverlight toolkit Checkboxes in a TreeView example.
When a user clicks on a parent TreeViewItem I want all of the child items to be checked, as in the above example. This works fine when the parent is collapsed, clicking the checkbox puts a tick in the parent and when you expand the node all children have a tick in the checkbox.
However it doesn't work if the parent is expanded. None of the children are updated to have a tick in the checkbox, although the underlying data list is updated.
My XAML is as follows:
<sdk:HierarchicalDataTemplate x:Key="NodeTemplate" ItemsSource="{Binding Path=Contracts}">
<StackPanel Orientation="Horizontal" ToolTipService.ToolTip="{Binding Path=Name}">
<CheckBox IsTabStop="False" IsThreeState="{Binding Path=HasContracts}" IsChecked="{Binding Path=Selected, Mode=TwoWay}" Click="CheckBox_Click" />
<TextBlock Text="{Binding Path=Name}" Tag="{Binding Path=ID}"/>
</StackPanel>
</sdk:HierarchicalDataTemplate>
<sdk:TreeView x:Name="tvClientContract" ItemsSource="{Binding Path=ClientContracts, Mode=TwoWay}" ItemTemplate="{StaticResource NodeTemplate}"/>
This is bound to a List<ClientContract> and uses the same code behind as in the linked example.
The ClientContract object is:
public int ID { get; set; }
public string Name { get; set; }
public List<ClientContract> Contracts { get; set; }
public bool? Selected { get; set; }
How can I force the child to repaint itself as the underlying List<ClientContract> object is updated?
If you want to use INotifyPropertyChange(what I did instead of using ObservableCollection) here is how you do it per example on the ID element:
public class myclass : INotifyPropertyChanged
{
private int id_Value;
public int ID
{
get { return id_Value; }
set
{
id_Value = value;
NotifyPropertyChanged("ID");
}
}
public string Name { get; set; }
public List<ClientContract> Contracts { get; set; }
public bool? Selected { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string name)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
I hope this helps if it was what you were trying to do.
Try using ObservableCollection<ClientContract> instead of a List<>. Usually you want to databind to this collection type instead when the data is dynamic so it can notify the UI of collection changes.

Resources