开发者

WPF Treeview contextmenu IsChecked binding MVVM

开发者 https://www.devze.com 2022-12-24 15:35 出处:网络
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 e开发者_Go百科ach treeitem is bou

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 e开发者_Go百科ach 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}}}


    <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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号