Reputation: 211
I have problem with data binding in MenuItem that is placed in ContextMenu. Here is a simple example how to reproduce this issue:
<Window x:Class="test_app.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:test_app"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid Background="Black">
<Grid.Resources>
<ContextMenu x:Key="PART_ContextMenu" >
<MenuItem Header="Element" Foreground="DarkGreen">
<MenuItem.Icon>
<Rectangle Width="20" Height="20" Fill="{Binding Foreground, RelativeSource={RelativeSource AncestorType=MenuItem}}" />
</MenuItem.Icon>
</MenuItem>
</ContextMenu>
<Menu x:Key="PART_Menu">
<MenuItem Header="Element" Foreground="DarkGreen">
<MenuItem.Icon>
<Rectangle Width="20" Height="20" Fill="{Binding Foreground, RelativeSource={RelativeSource AncestorType=MenuItem}}" />
</MenuItem.Icon>
</MenuItem>
</Menu>
</Grid.Resources>
<Grid.RowDefinitions>
<RowDefinition Height="20"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StaticResource ResourceKey="PART_Menu" />
<TextBlock Grid.Row="1" Text="test Text" Foreground="White" ContextMenu="{StaticResource PART_ContextMenu}"/>
</Grid>
Both menus are created as a resource of a grid to ensure it works the same way. I want to bind the Foreground brush of the MenuItem to the Fill brush of the icon. This works perfectly in case of the Menu but NOT for the ContextMenu. There is no green rectangle. If I replace the binding with a color it works. I added the following line the main window c'tor to get more information
System.Diagnostics.PresentationTraceSources.DataBindingSource.Switch.Level = System.Diagnostics.SourceLevels.Critical;
But wpf does not report any data binding error, warning or information. Can anyone explain what happen here?
Cheers
Upvotes: 2
Views: 181
Reputation: 61
When running your example (VS2015 Update 1) I do see a reported binding error:
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.MenuItem', AncestorLevel='1''. BindingExpression:Path=Foreground; DataItem=null; target element is 'Rectangle' (Name=''); target property is 'Fill' (type 'Brush')
Changing the StaticResource in the TextBlock to DynamicResource, it works as intended. However, I don't know why!
Upvotes: 1