【发布时间】:2010-12-18 05:53:04
【问题描述】:
我一直在尝试制作一个简单的用户控件来显示图像,并最终让它在我的 WPF 应用程序中充当按钮。
我将这些用户控件之一写入表单的 XAML,并且始终显示图像。但是,当以编程方式将它们添加到堆栈面板时,控件在那里,但图像从未显示。
这是 UserControl:(简单,但适用于本示例)
<UserControl x:Class="ImgButton"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
MinHeight="32" MinWidth="32"
x:Name="uc_ImgButton">
<Border BorderBrush="Gray" BorderThickness="2">
<Image Source="{Binding ElementName=uc_ImgButton, Path=Source}" x:Name="img"/>
</Border>
</UserControl>
我将 Source 属性设置为 ImageSource 类型的依赖属性:
Partial Public Class ImgButton
Public Property Source() As ImageSource
Get
Return GetValue(SourceProperty)
End Get
Set(ByVal value As ImageSource)
SetValue(SourceProperty, value)
End Set
End Property
Public Shared ReadOnly SourceProperty As DependencyProperty = _
DependencyProperty.Register("Source", _
GetType(ImageSource), GetType(ImgButton))
End Class
这是我如何在 VB 中以编程方式添加它们的示例:
Dim newBtn As New myApp.ImgButton
newBtn.Width = 100
newBtn.Height = 100
Dim bi As New BitmapImage
bi.BeginInit()
bi.UriSource = New Uri("C:\test.png", UriKind.RelativeOrAbsolute)
bi.EndInit()
'MsgBox(bi.Width) '(a simple debug test I added)
newBtn.Source = bi
Me.StackPanelMain.Children.Add(newBtn)
这是奇怪的部分......如上所示的代码运行没有错误,但我的表单上的结果是一个空边框,里面没有显示图像。
但是,如果您取消注释 MsgBox 行,现在将显示图像。就好像强迫它从 BitmapImage 获得一些价值使它工作。我还尝试用“dim x as integer = bi.PixelWidth”之类的无害的东西替换 MsgBox 行,并且还使图像显示。如果我把它拿走,我的表格上就没有图像了。
我怀疑我遗漏了什么,或者只是不明白什么。我想了解发生了什么,而不是在我的应用中留下看似毫无意义的代码行。
【问题讨论】:
标签: wpf vb.net image user-controls