WPF Databinding ContextMenu of Button inside a DataTemplate inside an ItemsControl - c#

I am trying to figure out how I can bind the ContextMenu of the Button that is being added in the ItemsControl I have. Basically, I'm wanting to be able to right click on a button and remove it from the observable collection that sits on my viewmodel. I understand that ContextMenu's are not part of the VisualTree, so using RelativeSource to walk up the tree to find my DataContext hasn't been useful to me.
The end goal of what I want to do is Bind the Command on the MenuItem to the RemoveCommand on my ViewModel and then pass in the Content property of the Button that you right click on so that I can remove it from the observable collection.
Any help on this would be greatly appreciated.
Model:
public class Preset
{
public string Name { get; set; }
}
ViewModel:
public class SettingsWindowViewModel
{
public ObservableCollection<Preset> MyPresets { get; } = new ObservableCollection<Preset>();
private ICommand _plusCommand;
public ICommand PlusCommand => _plusCommand ?? (_plusCommand = new DelegateCommand(AddPreset));
private ICommand _removeCommand;
public ICommand RemoveCommand => _removeCommand ?? (_removeCommand = new DelegateCommand<string>(RemovePreset));
private void AddPreset()
{
var count = MyPresets.Count;
MyPresets.Add(new Preset {Name = $"Preset{count+1}"});
}
private void RemovePreset(string name)
{
var preset = MyPresets.FirstOrDefault(x => string.Equals(x.Name, name, StringComparison.CurrentCultureIgnoreCase));
if (preset!= null)
{
MyPresets.Remove(preset);
}
}
}
XAML:
<Window x:Class="WpfTesting.Esper.Views.SettingsWindow"
x:Name="MainSettingsWindow"
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:viewModels="clr-namespace:WpfTesting.Esper.ViewModels"
mc:Ignorable="d"
Title="SettingsWindow" Height="470" Width="612">
<Window.DataContext>
<viewModels:SettingsWindowViewModel/>
</Window.DataContext>
<Window.Resources>
<Style BasedOn="{StaticResource {x:Type MenuItem}}" TargetType="{x:Type MenuItem}" x:Key="PopupMenuItem">
<Setter Property="OverridesDefaultStyle" Value="True"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type MenuItem}">
<Border>
<ContentPresenter ContentSource="Header"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="1*"/>
<RowDefinition Height="35"/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="2" Orientation="Horizontal">
<Button Width="70" Content="Load"/>
<Button Width="70" Content="Save As"/>
<ItemsControl ItemsSource="{Binding MyPresets}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Width="70" Content="{Binding Name}">
<Button.ContextMenu>
<ContextMenu>
<MenuItem Style="{StaticResource PopupMenuItem}" Header="Remove">
<!--
I need to set up binding a Command to a method on the DataContext of the Window, and I need to pass in the Content of the Button that is the parent of the ContextMenu
-->
</MenuItem>
</ContextMenu>
</Button.ContextMenu>
</Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<Button Width="20" Background="Transparent" BorderBrush="Transparent" Content="+" FontSize="21.333" HorizontalAlignment="Center" VerticalAlignment="Center" Command="{Binding PlusCommand}"/>
</StackPanel>
</Grid>
</Window>

Using WPF: Binding a ContextMenu to an MVVM Command as an introduction to what Tags can do, I figured out how to do what I was looking for by using multiple Tags to save the Context of what I was looking for.
I first made sure to give my window a x:Name
<Window x:Name="MainSettingsWindow"
Next, on the Button inside my DataTemplate of my ItemsControl, I set a Tag and set it to my Window
<ItemsControl ItemsSource="{Binding MyPresets}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Width="70" Content="{Binding Name}" Tag="{Binding ElementName=MainSettingsWindow}">
Next, in the ContextMenu, I seth the DataContext of the ContextMenu to the Tag I set on the Button, I also needed to create a Tag on the ContextMenu and point it back to the Content Property of the Button so that I can pass that into the CommandParameter
<ContextMenu DataContext="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource Mode=Self}}" Tag="{Binding PlacementTarget.Content, RelativeSource={RelativeSource Mode=Self}}">
At this point, I can now bind my MenuItem correctly using the Command from my ViewModel and the Content Property from the Button
This is the final XAML for my ItemsControl:
<ItemsControl ItemsSource="{Binding MyPresets}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Width="70" Content="{Binding Name}" Tag="{Binding ElementName=MainSettingsWindow}">
<Button.ContextMenu>
<ContextMenu DataContext="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource Mode=Self}}" Tag="{Binding PlacementTarget.Content, RelativeSource={RelativeSource Mode=Self}}">
<MenuItem Header="Remove"
Style="{StaticResource PopupMenuItem}"
Command="{Binding Path=DataContext.RemoveCommand}"
CommandParameter="{Binding Path=Tag, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}"/>
</ContextMenu>
</Button.ContextMenu>
</Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
One thing to note is that I had to change the CommandParameter on my ViewModel to take an Object instead of a String. The reason I did this was because I was getting an exception on the CanExecute method in my DelegateCommand
This is the exception I was getting:
Unable to cast object of type 'MS.Internal.NamedObject' to type 'System.String'.
I'm not sure exactly what's causing that exception to throw, but changing it to Object works ok for me.

I had basically a similar problem, and the solution I found was to use the Messenger class some MVVM frameworks like Devexpress or Mvvm Light have.
Basically you can register in a viewModel to listen for incoming messages. The class itself, at least in the Devexpress implementation works with weak references, so you may not even unregister message handlers and it will not cause memory leaks.
I had used this method for removing on right click tabs from a ObservableCollection, so it was similar to your scenario.
You can have a look here :
https://community.devexpress.com/blogs/wpf/archive/2013/12/13/devexpress-mvvm-framework-interaction-of-viewmodels-messenger.aspx
and here :
https://msdn.microsoft.com/en-us/magazine/jj694937.aspx

Related

C# MVVM: MenuItem Command don´t execute in ViewModel

I created a Delete MenuItem and binding a command to it.
Now I have the problem, if I am pressing the Delete MenuItem, nothing happens. Also if the program is executed with the debugger, it never reaches the private void DeleteItem.
xaml:
<ListBox.ItemTemplate>
<DataTemplate>
<Border Background="#F5F5F5" Width="80" Height="60" Margin="0,5,5,5">
<Border.ContextMenu>
<ContextMenu>
<MenuItem Header="Delete"
Command="{Binding Path=DeleteItemCommand, RelativeSource={RelativeSource FindAncestor, AncestorType= MenuItem}}">
<MenuItem.Icon>
<Label FontFamily="#FontAwesome" Content="" />
</MenuItem.Icon>
</MenuItem>
</ContextMenu>
</Border.ContextMenu>
ViewModel:
public ICommand DeleteItemCommand { get; set; }
DeleteItemCommand = new RelayCommand(DeleteItem);
private void DeleteItem(object obj)
{
try
{
// Do Magic
}
catch (Exception)
{
MessageBox.Show(error);
}
}
Would be great, if someone could help me or have any ideas how to solve it, because i can´t find the error.
ContextMenu is indeed not part of the visual tree. But I think because of that reason RelativeSource will not work because the binding will look up to the visual tree for the datacontext. contextMenu is not part of that visual tree so it will not find the proper datacontext. I've found a solution for this in the past using a proxy element in the resources for the window. Then set this proxyelement as content for a hidden contentcontrol in the window. On the menuItem set the CommandBinding to Datacontext.DeleteCommand and the soure to the static resource proxyelement. It is a bit hackish, but it works.
So to show some xaml, try this:
First in the resources of the window create a frameworkelement with the datacontext set to the windows datacontext (the viewmodel)
<Window.Resources>
<FrameworkElement x:Key="ProxyElement" DataContext="{Binding}"/>
</Window.Resources>
Then use the resource for the content of a collapsed content control. And set the proper binding to the menuItem. Something like this:
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<ContentControl Visibility="Collapsed" Content="{StaticResource ProxyElement}"/>
<ListBox x:Name="lbTest" Grid.Row="1">
<ListBox.ItemTemplate>
<DataTemplate>
<Border Background="#F5F5F5" Width="80" Height="60" Margin="0,5,5,5">
<Border.ContextMenu>
<ContextMenu>
<MenuItem Header="Delete"
Command="{Binding DataContext.DeleteCommand, Source={StaticResource ProxyElement}}">
<MenuItem.Icon>
<Label FontFamily="#FontAwesome" Content="" />
</MenuItem.Icon>
</MenuItem>
</ContextMenu>
</Border.ContextMenu>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
This should work. Give it a try.
Not sure if this will help but try using Binding instead of Binding Path.
ContextMenu is not part of VisualTree, that's why the binding fails. You can use some kind of relay like ContextMenu.PlacementTarget.Tag.Property as a cache for the second trail of binding search.
<ContextMenu>
<MenuItem Command="my:ImgTreeView.Folders" Header="Folders"
IsEnabled="{Binding Path=PlacementTarget.Tag.IsCheckFolder, RelativeSource={RelativeSource AncestorType=ContextMenu}}">
<MenuItem.Icon>
<Image Source="StarFolders.png" />
</MenuItem.Icon>
</MenuItem>
<!-- ... -->
</ContextMenu>

Double click event command not always executed

I'm quite new to WPF and C#. I'm trying to catch a double click event in an user control and handle it through an ICommand.
Here is how i'm trying to do that:
User Control:
<UserControl x:Class="MyNamespace.View.MyUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:local="clr-namespace:MyNamespace.View"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase"
DataContext="{Binding MyViewModelClass, Source={StaticResource Locator}}"
>
<UserControl.Resources>
<DataTemplate x:Key="MyTemplate">
<ContentControl>
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
<i:InvokeCommandAction Command="{Binding DataContext.HandleDoubleClickCommand, RelativeSource={RelativeSource AncestorType=UserControl}}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<WrapPanel HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="12" >
<TextBlock Text="Data: "><Run FontWeight="Light" Text="{Binding data}"/></TextBlock>
</WrapPanel>
</ContentControl>
</DataTemplate>
</UserControl.Resources>
<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="{DynamicResource ColorPanel2}">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Border Grid.Row="0" BorderThickness="0 0 0 1">
<WrapPanel Margin="12" VerticalAlignment="Center">
<TextBlock FontWeight="Bold" Margin="8" VerticalAlignment="Center" FontSize="18"
Text="some text: ">
</TextBlock>
</WrapPanel>
</Border>
<ListView Grid.Row="1"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
ItemsSource="{Binding SelectedItem.listElement, UpdateSourceTrigger=PropertyChanged}"
ItemTemplate="{StaticResource MyTemplate}"
SelectedItem="{Binding SelectedItem}"
/>
</Grid>
</UserControl>
And i placed the command to handle the event in the ViewModel class:
ICommand _HandleDoubleClickCommand;
public ICommand HandleDoubleClickCommand
{
get
{
if (_HandleDoubleClickCommand == null)
{
_HandleDoubleClickCommand = new RelayCommand<object>(ExecuteHandleDoubleClickCommand, CanExecuteHandleDoubleClickCommand);
}
return _HandleDoubleClickCommand;
}
}
private bool CanExecuteHandleDoubleClickCommand(object arg)
{
return true;
}
private void ExecuteHandleDoubleClickCommand(object obj)
{
System.Windows.MessageBox.Show("HandleDoubleClickCommand");
}
So, basically i have a list of elements and i want to handle the double click event on is.
The behavior i see is that sometimes the HandleDoubleClickCommand gets executed, sometimes it's not. I don't see any exception thrown and i checked with the debugger that the code is executed only when the message box is shown.
I also tried to use InputBindings instead of Interaction.Triggers:
<ContentControl.InputBindings>
<MouseBinding MouseAction="LeftDoubleClick"
Command="{Binding DataContext.HandleDoubleClickCommand, RelativeSource={RelativeSource AncestorType=UserControl}, diag:PresentationTraceSources.TraceLevel=High}" />
But i see the same behavior. Enabling the TraceLevel=High didn't give me useful info..
Also, i tried to handle the right click event instead of the double click, but still, the command gets executed only sometimes.
I think i'm missing something here, could someone help me to understand what the issue is? or at least give me some advice on how i can debug the problem..
Thank you
UPDATE
I found out that the command gets always executed if i double click on the element text. The thing is that i would like it to be executed even if i double click on an empty space of the selected row of the ListView...
Move the Margin from the WrapPanel to the TextBlock and define an ItemContainerStyle that makes the contents of the ListViewItem stretch horizontally.
You should also set the Background property of the WrapPanel to capture the clicks:
<ListView Grid.Row="1"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
ItemsSource="{Binding SelectedItem.listElement}"
SelectedItem="{Binding SelectedItem}">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
</ListView.ItemContainerStyle>
<ListView.ItemTemplate>
<DataTemplate>
<ContentControl>
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
<i:InvokeCommandAction Command="{Binding DataContext.HandleDoubleClickCommand,
RelativeSource={RelativeSource AncestorType=UserControl}}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<WrapPanel Background="Transparent">
<TextBlock Text="Data: " Margin="12"><Run FontWeight="Light" Text="{Binding data}"/></TextBlock>
</WrapPanel>
</ContentControl>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

Method in ContextMenu for (Hierarchical)DataTemplate calls TreeViewItem's method instead of the one in ViewModel

I have a TreeView with multiple HierarchicalDataTemplate & DataTemplate items and I'm using Caliburn Micro for mvvm. The ItemsSource for the treeview is pointing to a collection in the viewmodel called 'TreeData' and I tried adding a specific ContextMenu for each HierarchicalDataTemplate & DataTemplate.
In the ContextMenu I use the caliburn functionality "cal:Message.Attach" to call a function in the
I made a smaller example of the treeview to illustrate the problem.
In the ViewModel (the collection object):
public class MyViewModel
{
// TreeData object
public ObservableCollection<TestRoot> TreeData = new ObservableCollection<TestRoot>()
{
new TestRoot()
{
Name = "Root item"
}
};
// the function on the viewmodel that should be called
public void DoSomething(object item)
{
MessageBox.Show("MyViewModel - DoSomething called");
}
}
The collection object:
public class TestRoot
{
public string Name { get; set; }
// caliburn calls this instead of the one on the viewmodel
public void DoSomething(object item)
{
MessageBox.Show("TestRoot - DoSomething called");
}
}
MyView.xaml treeview with only one (Hierarchical)DataTemplate:
<TreeView Margin="5" ItemsSource="{Binding TreeData}">
<TreeView.Resources>
<DataTemplate DataType="{x:Type vm:TestRoot}" >
<StackPanel Orientation="Horizontal">
<StackPanel.ContextMenu>
<ContextMenu>
<!-- caliburn (?) chooses the method on the collection object, not the viewmodel -->
<MenuItem Header="test dosomething" cal:Message.Attach="DoSomething($dataContext)"></MenuItem>
</ContextMenu>
</StackPanel.ContextMenu>
<TextBlock Text="{Binding Name}"/>
</StackPanel>
</DataTemplate>
</TreeView.Resources>
</TreeView>
In another piece of code, I placed the ContextMenu in the TreeView.ContextMenu. There it worked as it 'should', pointing to the method on the viewmodel.
Looking around for a solution, I see things like "inheritance context". I think it might have something to do with it, but I'm not sure. How can I tell caliburn it must look in the viewmodel for my method, instead of the item in the TreeView I clicked on?
Or is there another possibility? For example: defining the different ContextMenus in the Resources and pointing them to the DataTemplates? But, wont that cause the exact same problem?
Please note that I'd like to keep the code-behind as minimal as possible. Thanks
update
For the completeness, here's the real development code. This should be right, no?
<TreeView ItemsSource="{Binding OrderTreeViewData.OrderTreeViewCategories}"
cal:Message.Attach="[Event SelectedItemChanged] = [Action OnSelectedItemChanged($this)]">
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<!-- We have to select the item which is right-clicked on -->
<EventSetter Event="TreeViewItem.PreviewMouseRightButtonDown"
Handler="TreeViewItem_PreviewMouseRightButtonDown"/>
<!-- set expanded -->
<Setter Property="TreeViewItem.IsExpanded" Value="True"/>
</Style>
</TreeView.ItemContainerStyle>
<TreeView.Resources>
<!-- dredge nodes -->
<HierarchicalDataTemplate DataType="{x:Type programs:DredgeRoot}"
ItemsSource="{Binding Dredgezones}">
<StackPanel>
<StackPanel.ContextMenu>
<ContextMenu DataContext="{Binding Path=PlacementTarget, RelativeSource={RelativeSource Self}}">
<MenuItem Header="Add dredge zone" cal:Message.Attach="TreeViewAddDredgeZone($datacontext)"></MenuItem>
</ContextMenu>
</StackPanel.ContextMenu>
<TextBlock Text="{Binding Name}"/>
</StackPanel>
</HierarchicalDataTemplate>
<!-- omitted other templates -->
</TreeView.Resources>
</TreeView>
Unfortunately there is still one tricky part to deal with. Due to the specific Popup behavior it doesn't inherit DataContext. To access proper context you have to get the PlacementTarget:
<StackPanel Tag="{Binding DataContext, RelativeSource={RelativeSource Self}}">
<StackPanel.ContextMenu>
<ContextMenu DataContext="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
<MenuItem Header="test dosomething" cal:Message.Attach="DoSomething"/>
</ContextMenu>
</StackPanel.ContextMenu>
</StackPanel>
I think you have the nearly same problem as me, maybe see this topic : Bind contextMenu to a different viewmodel from treeview
You can try to use a command :
Try to change you code to :
<ContextMenu x:Key="MyContextMenu">
<MenuItem Header="Add dredge zone" Command="{Binding PlacementTarget.Tag.DataContext.TreeViewAddDredgeZoneCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}"
CommandParameter="{Binding}"></MenuItem>
</ContextMenu>
Then add to your hierarchicalDataTemplate a Tag and ContextMenu
<HierarchicalDataTemplate DataType="{x:Type programs:DredgeRoot}"
ItemsSource="{Binding Dredgezones}" Tag="{Binding RelativeSource={RelativeSource AncestorType=UserControl}} ContextMenu="{StaticResource MyContextMenu}">
And in your viewmodel you can add your command with something like this :
public ICommand TreeViewAddDredgeZoneCommand
{
//your code here
}

Create buttons programmatically with unique id

I have created some buttons by first filling a class containing get/set methods and then using that info in XAML.
C#
List<MediaDetail> movies = new List<MediaDetail>();
...
...
MovieListView.ItemsSource = movies;
XAML
<Window.Resources>
<DataTemplate x:Key="ItemTemplate">
<WrapPanel Orientation="Vertical" Width="Auto">
<Button Width="200" Height="300" Click="SelectMovie_Click" Name ="NEED THIS TO BE DYNAMIC">
<Button.Template>
<ControlTemplate>
<Image Source="{Binding image}"/>
</ControlTemplate>
</Button.Template>
</Button>
<TextBlock Text="{Binding title}" HorizontalAlignment="Center"/>
</WrapPanel>
</DataTemplate>
</Window.Resources>
<ListView Name="MovieListView" ItemTemplate="{StaticResource ItemTemplate}" ItemsSource="{Binding Path = movies}" Margin="0,0,0,0" SelectionChanged="MovieListView_SelectionChanged" Grid.Row="1">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="5" />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
</ListView>
However the issue is, I need each button to have a unique id. I read elsewhere that this can't be done in XAML but I'm not sure how or where in my C# code to create these buttons.
I think the most flexible solution here would be to define a behavior:
public class UniqueNameBehavior : Behavior<FrameworkElement>
{
protected override void OnAttached()
{
base.OnAttached();
//assign unique name to the associated element, for example:
AssociatedObject.Name = Guid.NewGuid().ToString().Replace("-", null);
}
}
In XAML, attach this behavior to any element:
<Button>
<i:Interaction.Behaviors>
<local:UniqueNameBehavior/>
</i:Interaction.Behaviors>
</Button>
where xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" from System.Windows.Interactivity assembly.

WPF Caliburn.Micro ItemsControl ContextMenu don't find method

I'am really having some problems with the ContextMenu from Caliburn.Micro. No matter what I do, I get the error "Cant' find the method ...".
I've tried this solutions, and that one too, but I can't get this to work.
What I'am doing wrong? Actually, there's a way to debug the view and find out in which Context the control is searching for the respective ViewModel?
And another thing... this View is inside a DataTemplate from another view, does that change anything? All the others bindings are working from the correct ViewModel...
<ScrollViewer VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Disabled"
Grid.Row="1" Grid.Column="0"
Padding="10,5,15,5"
MaxHeight="390" x:Name="xImages">
<ItemsControl
ItemsSource="{Binding Path=Document.Images}"
dd:DragDrop.IsDragSource="True"
dd:DragDrop.IsDropTarget="True">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Height="110">
<Border Margin="5" BorderBrush="Gainsboro" BorderThickness="1">
<Image Source="{Binding Path=PathThumb}" Width="70" Height="100"> <!-- Tag="{Binding DataContext, ElementName=xImagens}" -->
<Image.ContextMenu>
<ContextMenu
cal:Action.TargetWithoutContext="{Binding DataContext, ElementName=xImagens}"> <!--PlacementTarget.Tag, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}"-->
<MenuItem Header="Ampliar"
cal:Message.Attach="[Event Click] = [Action ExpandImage($datacontext)]"></MenuItem>
<MenuItem Header="Excluir"
cal:Message.Attach="[Event Click] = [Action DeleteImage($datacontext)]"></MenuItem>
</ContextMenu>
</Image.ContextMenu>
</Image>
</Border>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal" ScrollViewer.HorizontalScrollBarVisibility="Disabled" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</ScrollViewer>
cal:Action.TargetWithoutContext="{Binding Source={x:Reference xImagens} , Path=DataContext}">
Because ContextMenu is not part of the VisualTree , you can't bind to elements in the visual tree
of it's TargetPlacement. ( Though in XAML it seems like it is part of it ).
You have two choices:
{Binding Path=PlacementTarget.DataContext}
Or:
{Binding Source={x:Reference xImagens}, Path=DataContext}
give the x:Name="xImages" to the ItemsControl and then do the binding with ElementName to the ContextMenu using the Action.TargetWithoutContext, you had it right but the ScrollViewer isn't what has the Datacontext to the List of data, the ItemControl does since it has the ItemSource.
Was there a reason for naming the ScrollViewer?
<ItemsControl x:Name="xImages">
<ContextMenu Action.TargetWithoutContext="{Binding Path=DataContext, ElementName=xImages}">
<!-- Shortened -->
</ContextMenu>
</ItemsControl>

Categories