我要实现这样一个功能
<ContextMenu x:Key="ContextMenuColoum"> <MenuItem Header="复制" Tag="{Binding 这里我要绑定父元素的Text属性值}" Click="MenCopy_Click" > <MenuItem.CommandBindings> <CommandBinding CanExecute="CommandBinding_CanExecute" Executed="CommandBinding_Executed" Command="Copy"> </CommandBinding> </MenuItem.CommandBindings> </MenuItem> </ContextMenu> <DataTemplate x:Key="dataTemplateName"> <TextBlock Text="{Binding Name}" ContextMenu="{ StaticResource ContextMenuColoum}"> </TextBlock> </DataTemplate>
我在MenuItem 中Tag属性绑定该怎么写?
用相对数据源。就是那个reference还是什么的那个,使得子元素对象的数据源对象是父元素。
本人菜鸟啊 具体该怎么实现?
@BoyLife: http://msdn.microsoft.com/zh-cn/library/system.windows.data.binding.relativesource(VS.90).aspx
Value="{Binding RelativeSource={x:Static RelativeSource.Self},
Path=(Validation.Errors)[0].ErrorContent}"/>
@BoyLife:
数据绑定(八)使用Binding的RelativeSource - iamsupercola的专...
Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorLevel=1, AncestorType={x:Type Grid}}, Path=Name}"
@笨笨蜗牛: 这个是我想要实现的功能
<ContextMenu x:Key="ContextMenuColoum">
<MenuItem Header="复制" Tag="{Binding Path=Text,RelativeSource={ RelativeSource Mode=FindAncestor, AncestorType={x:Type TextBlock}, AncestorLevel=1 }}" Click="MenCopy_Click" >
<MenuItem.CommandBindings>
<CommandBinding CanExecute="CommandBinding_CanExecute" Executed="CommandBinding_Executed" Command="Copy">
</CommandBinding>
</MenuItem.CommandBindings>
</MenuItem>
</ContextMenu>
<DataTemplate x:Key="dataTemplateName">
<TextBlock Text="{Binding Name}" ContextMenu="{ StaticResource ContextMenuColoum}">
</TextBlock>
</DataTemplate>
这样写在后台获取不到Tag
我的后台
private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
MenuItem men = e.OriginalSource as MenuItem;//获取事件发起源
if (men != null)
{
e.CanExecute = true;
}
else
{
e.CanExecute = false;
}
}
private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
MenuItem men = e.OriginalSource as MenuItem;//获取事件发起源
if (men != null && men.Tag!=null)
{
Clipboard.SetText(men.Tag.ToString());
}
}
private void MenCopy_Click(object sender, RoutedEventArgs e)
{
MenuItem men = e.OriginalSource as MenuItem;//获取事件发起源
if (men != null && men.Tag != null)
{
Clipboard.SetText(men.Tag.ToString());
}
}
@BoyLife: WPF如何获取ContextMenu的源控件属性 - .NET技术 / C#
@无之无: 好使~