【问题标题】:WPF data binding with MenuItem in ContextMenuWPF 数据绑定与 ContextMenu 中的 MenuItem
【发布时间】:2015-12-22 11:31:51
【问题描述】:

我在放置在 ContextMenu 中的 MenuItem 中的数据绑定有问题。 这是一个如何重现此问题的简单示例:

<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>

两个菜单都是作为网格资源创建的,以确保其工作方式相同。 我想将 MenuItem 的 Foreground 画笔绑定到图标的 Fill 画笔。这在菜单的情况下非常有效,但不适用于 ContextMenu。没有绿色矩形。如果我用一种颜色替换绑定,它会起作用。 我在主窗口 c'tor 中添加了以下行以获取更多信息

System.Diagnostics.PresentationTraceSources.DataBindingSource.Switch.Level = System.Diagnostics.SourceLevels.Critical;

但是 wpf 不报告任何数据绑定错误、警告或信息。 谁能解释一下这里发生了什么?

干杯

【问题讨论】:

    标签: wpf data-binding


    【解决方案1】:

    在运行您的示例(VS2015 Update 1)时,我确实看到了一个报告的绑定错误:

    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')

    将 TextBlock 中的 StaticResource 更改为 DynamicResource,它按预期工作。但是,我不知道为什么!

    【讨论】:

    • 我的系统也没有错误。但是改用 DynamicResource 解决了这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-04
    • 2011-06-22
    • 1970-01-01
    • 1970-01-01
    • 2017-07-27
    • 2016-10-18
    相关资源
    最近更新 更多