我一直在试图做一个简单的用户控件来显示图像,并最终使其充当我的WPF应用程序中的按钮。是什么让这个图像显示在我的WPF usercontrol中?
我有一个这样的用户控件写入表单的XAML,并且图像总是显示。但是,当以编程方式将它们添加到堆栈面板时,控件在那里,但图像从不显示。
这里的用户控件:(简单,但适用于本示例)
<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)
这是奇怪的部分...代码a如上所示运行没有错误,但我的表单上的结果是空的边框,没有图像显示在里面。
但是,如果您取消注释MsgBox行,现在图像显示。就好像迫使它从BitmapImage中获得一些价值使它起作用。我也尝试用像“dim x as integer = bi.PixelWidth”这样的不可思议的东西替换MsgBox行,并且还将图像显示出来。如果我把它拿走,我的表格上没有图像。
我怀疑我错过了什么,或者只是不明白。我想知道发生了什么,而不是在我的应用程序中留下看似毫无意义的代码行。
在我的WPF体验的这一点上,我的大部分工作都是基于我在网上找到的代码片段来让我开始。我只想要一个拥有属性的用户控件,我可以设置它来更改显示在其中的图像。如果有更好的方法来完成这个任务,请免费分享,我想学习:-)我不太了解你的建议...示例代码会有所帮助。 – 2009-07-28 18:22:43