繁体   English   中英

WPF - 绑定到菜单图标

[英]WPF - Binding to a Menu Icon

我有一个包含菜单的 UserControl。 我需要将 Menu.Icon 绑定到 UserControl 的属性,但它不起作用。

代码是这样开始的 -

        <Border Grid.Row="0">            
        <DockPanel>
            <Image x:Name="testImage" Height="16" Width="16" Source="{Binding ElementName=UC,Path=AddImage}"/>
            <Menu DockPanel.Dock="Left" Height="20"
              VerticalAlignment="Center">
                <MenuItem Header="{Binding ElementName=UC,Path=AddText}">
                    <MenuItem.Icon>
                        <!--<Image x:Name="workswhenin" Height="16" Width="16" Source="pack://application:,,/Kowdox;component/Images/UserIcons/user_add.png"/>-->

                        <Image x:Name="realImage" Height="16" Width="16"
                        Source="{Binding ElementName=UC,Path=AddImage}"/>
                    </MenuItem.Icon>
                </MenuItem>

您看到声明的第一张图片 (testImage) 完美运行,所以我很高兴绑定是正确的。 第二个图像(注释掉并命名为“workswhenin”)包含我传递给 UserControls 绑定属性的包 URI,它也可以工作,但第三个(realImage)根本没有出现!

我看不出它不应该起作用的任何原因; 我知道绑定很好,并且我知道图像在标记中的位置很好,所以发生了什么?

任何帮助将不胜感激。 提前致谢。

无法确定,因为我看不到您的代码,但我很确定我知道问题出在哪里。

Image.Source需要一个ImageSource类型的 object 。 When you specify the URL in XAML a default WPF converter is used to convert the URL into an ImageSource object. 因为您使用的是绑定,所以不使用默认转换器。 因此,您可能正在尝试将图像源设置为 URL 值,而不是ImageSource object。

在您的属性代码中,您将不得不创建一个ImageSource object,这真的很痛苦。 您可以创建一个BitmapImage并传入 URL。

最简单的解决方案是在要绑定的属性的代码隐藏中使用 Microsoft 的默认转换器,或者在绑定中显式使用它。 该转换器称为ImageSourceConverter

编辑:

这是一个简单的例子:

绑定源内的代码:

public ImageSource AddImageSource
{
    get
    {
        ImageSourceConverter imgConv = new ImageSourceConverter();
        return imgConv.ConvertFrom(this.AddImage);
    }
}

更新绑定以针对此属性而不是 AddImage 属性。 确保在 AddImage 属性更改时也为此属性触发 PropertyChanged 事件。

没有花时间为此构建测试场景,但它应该可以正常工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM