views:

676

answers:

1

I've got a TreeView to which I associate a ContextMenu. That contextmenu has an item whose IsChecked property I want to bind to my ViewModel. Since I am using a tree each treeitem is bound to a subproperty of my ViewModel.

In the VS2010 output window I am seeing this databinding error:

BindingExpression path error: 'IsAutoStart' property not found on 'object' ''HostMgmtViewModel' (HashCode=12565727)'. BindingExpression:Path=IsAutoStart; DataItem='HostMgmtViewModel'

This clearly shows it is trying to bind to my ViewModel and not to the treeitem's associated data. How do I bind to the correct object? Remember my contextmenu is associated with the whole TreeView not to the specific treeitem.

---------- Edit

As xandy pointed out below the resolution to my problem was to bind the IsChecked like this:

{Binding Path=PlacementTarget.SelectedItem.IsDisabledStart, Mode=OneWay, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}
+1  A: 
    <TreeView Name="tview" Grid.Row="0" Tag="{Binding RelativeSource={RelativeSource Self}, Path=SelectedItem}">
        <TreeView.ContextMenu>
            <ContextMenu>
                <MenuItem Name="miC" Header="{Binding Path=Tag.Key}" DataContext="{Binding Path=PlacementTarget, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}"></MenuItem>
            </ContextMenu>
        </TreeView.ContextMenu>
    </TreeView>

This is the working code snippet I have. Courtesy of [this].1 All you need is to change the binding path in the tag. I am currently binding the Treeview to a dictionary, so it is the Key property of it. It should not have any problem in binding to any object collections. One interesting finding is context menu is not in part of element tree and this cause the problem. I could bind the text box with no problem:

    <TextBlock Grid.Row="1" DataContext="{Binding ElementName=tview, Path=SelectedItem}">
        <TextBlock.Text>
            <Binding Path="Key" />
        </TextBlock.Text>
    </TextBlock>

But it is not functioning if for menuitem if I put the same thing.

xandy
And this binding goes within the ContextMenu? When I try that I get this error: A 'Binding' cannot be used within a 'ItemCollection' collection. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.
BrettRobi
BTW, My previous answer is suppose to do like the textblock example above, but apply on the menuitem header. No error is encountered with the menuitem but it is not working. You get DependencyObject... error coz you are binding to the data source, but not the property.
xandy
Thanks xandy, your sample gave me the right answer. I ended up binding the menu item IsChecked to this:{Binding Path=PlacementTarget.SelectedItem.IsAutoStart, Mode=OneWay, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}
BrettRobi