![](/img/trans.png)
[英]How can I bind a Hold/DoubleTap event of a button to a property in ViewModel
[英]In Button Click Context Menu How do I bind to viewModel?
我有一個按鈕,單擊該按鈕會打開一個上下文菜單,現在單擊上下文菜單將綁定到viewModel。 但是它沒有發生。
<Button Content="Copy" Tag="{Binding LinkViewModel, RelativeSource={RelativeSource Mode=Self}}" Command="{Binding LinkCopyCommand, UpdateSourceTrigger=PropertyChanged}" >
<Button.ContextMenu>
<ContextMenu>
<MenuItem Header="Copy Download link " Command="{Binding Path=Parent.PlacementTarget.Tag.CopyViewCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}" />
<MenuItem ... />
</ContextMenu>
</Button.ContextMenu>
</Button>
我已經嘗試了標簽屬性,但在我看來它不起作用。 如果綁定到按鈕本身,則viewmodel可以正常工作,但是contextMenu dataBinding無法正常工作。
編輯:
現在,由於代碼在討論之后正在工作,我想將其發布在這里。
我所做的更改是,我將UpdateSourceTrigger =“ Propertychanged”放在此處,將代碼
<Button Content="Copy" Tag="{Binding LinkViewModel, RelativeSource={RelativeSource Mode=Self}}" Command="{Binding LinkCopyCommand, UpdateSourceTrigger=PropertyChanged}" >
<Button.ContextMenu>
<ContextMenu Width="{Binding RelativeSource={RelativeSource Self}}">
<MenuItem Header="Copy View link " Command="{Binding CopyViewCommand, UpdateSourceTrigger=PropertyChanged}" />
<MenuItem ... />
</ContextMenu>
</Button.ContextMenu>
</Button>
但是我不知道它怎么突然起作用,在Button Context菜單的情況下它必須與tag屬性一起工作。 如果有人對此有所了解,我認為許多像我這樣的人都是新的WPF和數據綁定的受益者。
我假設您正在UserControl
中使用此Button。 請嘗試以下代碼
<Button Content="Copy" Tag="{Binding LinkViewModel, RelativeSource={RelativeSource Mode=Self}}" Command="{Binding LinkCopyCommand, UpdateSourceTrigger=PropertyChanged}" >
<Button.ContextMenu>
<ContextMenu>
<MenuItem Header="Copy Download link " Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.CopyViewCommand}" />
<MenuItem ... />
</ContextMenu>
</Button.ContextMenu>
</Button>
<Button Content="Copy" Command="{Binding LinkCopyCommand, UpdateSourceTrigger=PropertyChanged}" >
<Button.ContextMenu>
<ContextMenu>
<MenuItem Header="Copy Download link " Command="{Binding Path=CopyViewCommand}" />
<MenuItem ... />
</ContextMenu>
</Button.ContextMenu>
直接從您的DataContext
...(即ViewModel)綁定CopyViewCommand
。
您必須將ContextMenu的DataContext設置為ViewModel。 一種方法是為上下文菜單設置一個Opened事件處理程序。
在下面的鏈接中查看我的答案-
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.