我有一个包含菜单的 UserControl。我需要将 Menu.Icon 绑定(bind)到 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) 完美运行,所以我很高兴绑定(bind)是正确的。第二个图像(注释掉并命名为“workswhenin”)包含我传递给 UserControls 绑定(bind)属性的包 URI,它也可以工作,但第三个(realImage)根本没有出现!
我看不出它不应该起作用的任何原因;我知道绑定(bind)很好,并且我知道图像在标记中的位置很好,所以发生了什么?
任何帮助将不胜感激。
提前致谢。
最佳答案
无法确定,因为我看不到您的代码,但我很确定我知道问题出在哪里。Image.Source
需要 ImageSource
类型的对象.当您在 XAML 中指定 URL 时,默认 WPF 转换器用于将 URL 转换为 ImageSource
目的。因为您使用的是绑定(bind),所以不使用默认转换器。因此,您可能正在尝试将图像源设置为 URL 值而不是 ImageSource
。目的。
在您的属性代码中,您必须创建一个 ImageSource
对象,这真是一种痛苦。您可以创建一个 BitmapImage
并传入 URL。
最简单的解决方案是在要绑定(bind)到的属性的代码隐藏中使用 Microsoft 的默认转换器,或者在绑定(bind)中显式使用它。转换器称为 ImageSourceConverter
.
编辑:
这是一个简单的例子:
绑定(bind)源内的代码:
public ImageSource AddImageSource
{
get
{
ImageSourceConverter imgConv = new ImageSourceConverter();
return imgConv.ConvertFrom(this.AddImage);
}
}
更新绑定(bind)以针对此属性而不是 AddImage 属性。确保在 AddImage 属性更改时也为此属性触发 PropertyChanged 事件。
没有花时间为此构建测试场景,但它应该可以正常工作。
关于.net - WPF - 绑定(bind)到菜单图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/700681/