I have a DataTemplate for ListBoxItem that (should be) fairly simple, and just access via {Binding} the properties of my class.
Below is my class and code that creates a simple (dummy) ItemsSource of the ListBox.
public class ChatMessage
{
public string Message = "Testing Message";
public DateTime DateReceived = new DateTime(2011, 07, 16, 14, 00, 05);
public override string ToString()
{
return Message;
}
}
// ....
// Dummy Data
ObservableCollection<ChatMessage> chatItems = new ObservableCollection<ChatMessage>();
for (int i = 0; i < 20; i++)
chatItems.Add(new ChatMessage());
lbMessages.ItemsSource = chatItems;
Here’s my DataTemplate..
<DataTemplate x:Key="ChatItemListBox">
<Grid Width="362">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="26" />
</Grid.RowDefinitions>
<TextBlock Text="{Binding Message}" />
<TextBlock Grid.Row="1"Text="{Binding DateReceived}"/>
</Grid>
</DataTemplate>
For some reason both TextBlocks are completely empty. However, if I change for example {Binding Message} to just {Binding} it will call ToString and show the message.
I know I must be missing something very simple..
Just in case it matters, the ListBox is defined as below:
<ListBox x:Name="lbMessages" Margin="0,8,0,72" ItemTemplate="{StaticResource ChatItemListBox}"/>
You should use properties, not fields.
This is because binding is using reflection for non-DependencyProperties, and doesn’t look for fields.
(This advice would solve the problem for WPF, but Silverlight may have some additional quirks.)