I've been trying to make a simple usercontrol to display an image, and eventually make it act as a button in my WPF application.
I had one of these usercontrols written into the form's XAML, and the image always displayed. However, when adding them programmatically to a stackpanel, the control was there but the image never displayed.
Here's the UserControl: (simple, but works for this example)
<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>
I set up the Source property as a dependency property of the ImageSource type:
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
Here's an example of how I add them programmatically in 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)
Here's the strange part... the code as shown above runs without error, but the result on my form is an empty border with no image displayed inside.
However, if you un-comment the MsgBox line, now the image displays. It's as if forcing it to get some value from the BitmapImage makes it work. I also tried replacing the MsgBox line with something innoculous like "dim x as integer = bi.PixelWidth" and that ALSO made the image display. If I take it away, no image on my form.
I suspect I'm missing something or just don't understand something. I'd like to learn what's going on, rather than leave a seemingly pointless line of code in my app.