I have a ListView which contains TextBlocks. The ListView has a context menu and I need to get the Content property of TextBlock when the context menu is clicked.
I need to get "Documents and Settings" when Download is clicked in the Context Menu. I've tried a number of solutions, but they all result in a Null Reference Exception. Thanks!
Here is an example of how I setup a ItemsControl to call a command and pass in the item via a commandparameter to do some work using MVVM Light.
<Window.Resources>
<h:BindingProxy x:Key="proxy" Data="{Binding}"></h:BindingProxy>
</Window.Resources>
<Grid>
<ItemsControl ItemsSource="{Binding MyData}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.ContextMenu>
<ContextMenu>
<MenuItem Header="Remove Me" Command="{Binding Data.MyCommand, Source={StaticResource proxy}}" CommandParameter="{Binding}"></MenuItem>
</ContextMenu>
</Grid.ContextMenu>
<TextBlock Grid.Column="0" HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding SomeField}"></TextBlock>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
I use a BindingProxy to bind the window datacontext for the context menu to get the command, here is the code for that.
/// <summary>
/// BindingProxy
/// Used to get Parent datacontext within Child control.
/// </summary>
public class BindingProxy : Freezable
{
#region " Overrides Of Freezable "
protected override Freezable CreateInstanceCore()
{
return new BindingProxy();
}
#endregion
#region " Data "
// Using a DependencyProperty as the backing store for Data. This enables animation, styling, binding, etc...
public static readonly DependencyProperty DataProperty = DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null));
public object Data
{
get { return (object)GetValue(DataProperty); }
set { SetValue(DataProperty, value); }
}
#endregion
}
As you can see, the CommandParameter just uses {Binding} to get the object for the row of the ItemsSource which is bound to an ObservableCollection<SomeClass>.
Hopefully this gives you some insight into setting up a context menu to do some work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.