1

I have a UserControl, defined like so:

<UserControl x:Name=userControlName>   
    <UserControl.Resources>      
        <Style TargetType="{x:Type MyControl}">
            <Setter Property="ContextMenu">
                <Setter.Value>
                    <ContextMenu >
                        <MenuItem Header="ITEM"
                                  Command="{Binding ElementName=userControlName, Path=DeleteCommand">                          
                        </MenuItem>
                    </ContextMenu>
                </Setter.Value>
            </Setter>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type controlType}">                        
                        <Grid>                            
                            <!--MyContentHere-->
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>        
        </Style>     
    </UserControl.Resources>

    <Grid>
       <!--Content -->
       <ListBox>
        <ListBoxItem> <!--is of Type MyControl-->
       </ListBox>
    </Grid>
</UserControl>

This does not work, as the userControlName's DataContext is not being found.

Am I missing something here?

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
user1202434
  • 2,243
  • 4
  • 36
  • 53
  • Try `PlacementTarget`. There are many samples at SO like http://stackoverflow.com/a/1022156/620360 or http://stackoverflow.com/a/5357124/620360. – LPL Jun 04 '12 at 22:55

1 Answers1

0

You should try using a WPF RelativeSource binding like such:

 <ContextMenu >
    <MenuItem Header="ITEM"
          Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Path=DataContext.DeleteCommand}">                          
    </MenuItem>
</ContextMenu>
SliverNinja - MSFT
  • 31,051
  • 11
  • 110
  • 173
  • Where are you assigning `DataContext`? You may have a problem with how your `DataContext` is being assigned. Take a [look at the Output Window](http://blogs.msdn.com/b/wpfsldesigner/archive/2010/06/30/debugging-data-bindings-in-a-wpf-or-silverlight-application.aspx) and share any databinding errors. – SliverNinja - MSFT Jun 04 '12 at 14:06