ContextMenu 内の UserControl の元の DataContext を取得するにはどうすればよいですか。
以下のコードでは、DataTemplate に Button があり、正しくバインドされていることがわかります。ただし、コンテキスト メニューのデータ ソースをバインドしようとすると、次のエラーが表示されます。
System.Windows.Data エラー: 4 : 参照 'RelativeSource FindAncestor、AncestorType='System.Windows.Controls.TreeView'、AncestorLevel='1'' でバインディングのソースが見つかりません。BindingExpression:Path=DataContext; DataItem=null; ターゲット要素は 'ContextMenu' (Name='') です。ターゲット プロパティは 'DataContext' (タイプ 'Object') です
ContextMenu を ViewModel にバインドできるようにするにはどうすればよいですか?
================================================== =============================
ViewModel は分離コードでビューのデータ コンテキストに割り当てられます。
意見:
<TreeView ItemsSource="{Binding Clients}"
cmd:TreeViewSelect.Command="{Binding SelectionChangedCommand}"
cmd:TreeViewSelect.CommandParameter="{Binding RelativeSource={RelativeSource Self},Path=SelectedItem}">
<TreeView.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Name}">
<TextBlock.ContextMenu>
<ContextMenu DataContext="{Binding DataContext,
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type TreeView}}}">
<MenuItem Header="{Binding TestString}" />
</ContextMenu>
</TextBlock.ContextMenu>
</TextBlock>
<Button DataContext="{Binding DataContext,
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type TreeView}}}"
Content="{Binding TestString}" Command="{Binding EditSelectedClientCommand}" />
</StackPanel>
</DataTemplate>
</TreeView.ItemTemplate>
</TreeView>
ビューモデル:
public class ClientListViewModel : ViewModelBase
{
public String TestString {
get {
return "TESTING";
}
}
private ClientList _clients = null;
private readonly IClientService _clientService = null;
private readonly IEventAggregator _eventAggregator = null;
private Client _selectedClient = null;
private ICommand _selectionChangedCommand = null;
private ICommand _editSelectedClientCommand = null;
....
}