Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

wpf - Context Menu Binding to Parent Window's Datacontext

I have a TreeListControl that binds to a collection in my VM. I also want to define the context menu inside the treelistcontrol having its header text bind to another string in my VM. how can I set the data context in this case? I tried to

<Window.DataContext>
    <model:ViewModel></model:ViewModel>
</Window.DataContext>
<Grid>
<Button Grid.Row="1"  Command="{Binding CellCheckedCommand}"></Button>

    <TextBlock Text="{Binding HeaderText}" Grid.Row="2">
        <TextBlock.ContextMenu>
            <ContextMenu>
                <MenuItem DataContext="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=DataContext}"  Header="{Binding HeaderText}"></MenuItem>
            </ContextMenu>
        </TextBlock.ContextMenu>
    </TextBlock>
</Grid>

but it doesn't work.

Here is the ViewModel

public DelegateCommand CellCheckedCommand { get; set; }

private String _HeaderText;

public String HeaderText 
{
    get
    {
        return _HeaderText;
    }
    set
    {
        _HeaderText = value;
        NotifyPropertyChanged("HeaderText");
    }
}

public void NotifyPropertyChanged(String name)
{ 
    if(PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(name));
    }
}

private void CellCheckedMethod()
{
    HeaderText = "Changed";
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Provide a name for your window and explicitly bind to it such as

<window  x:Name="ReportsPage"/>

...

 <MenuItem DataContext="{Binding ElementName=ReportsPage}"/>

UPDATE

Since the context menu is actually in its own window, binding is a bit trickier. Hence the best bet is to walk up the RelativeSource to the context's parent and pull the header text from there:

    <Window.DataContext>
        <local:MainVM HeaderText="Jabberwocky" />
    </Window.DataContext>

    ...

<TextBlock Text="{Binding HeaderText}">
    <TextBlock.ContextMenu>
        <ContextMenu>

<MenuItem Header="{Binding Path=Parent.DataContext.HeaderText, 
                    RelativeSource={RelativeSource Self}}" />

        </ContextMenu>
    </TextBlock.ContextMenu>

Which for this context produces this

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...