Silverlight 2.0 - Binding a Domain Object to UserControl

I start with Silverlight. I want to display a list of messages in the user interface, but data binding does not work for me.

I have a message class:

public class Message { public string Text { get; set; } ... } 

I have a Silverlight User control with a Message dependency attribute:

 public partial class MessageDisplay : UserControl { public static readonly DependencyProperty MessageProperty = DependencyProperty.Register("Message", typeof(Message), typeof(MessageDisplay), null); public MessageDisplay() { InitializeComponent(); } public Message Message { get { return (Message)this.GetValue(MessageProperty); } set { this.SetValue(MessageProperty, value); this.DisplayMessage(value); } } private void DisplayMessage(Message message) { if (message == null) { this.MessageDisplayText.Text = string.Empty; } else { this.MessageDisplayText.Text = message.Text; } } } 

}

Then in the main xaml control I have

  <ListBox x:Name="MessagesList" Style="{StaticResource MessagesListBoxStyle}"> <ListBox.ItemTemplate> <DataTemplate> <Silverbox:MessageDisplay Message="{Binding}"></Silverbox:MessageDisplay> </DataTemplate> </ListBox.ItemTemplate> </ListBox 

And I link in the control.xaml.cs file:

  this.MessagesList.SelectedIndex = -1; this.MessagesList.ItemsSource = this.messages; 

Data binding does not give errors, and it seems that the list has the correct number of elements, but the breakpoint in the MessageDisplay Message property qualifier never hits, and the message is never displayed properly.

What did I miss?

+3
source share
1 answer

The Message property is probably set by the data binding, which bypasses your actual Message property (and not the dependent one). To fix this, add the PropertyChangedCallback property to this property.

 public static readonly DependencyProperty MessageProperty = DependencyProperty.Register("Message", typeof(Message), typeof(MessageDisplay), new PropertyMetadata( new PropertyChangedCallback(MessageDisplay.MessagePropertyChanged)); public static void MessagePropertyChanged(DependencyObject obj, DependecyPropertyChangedEventArgs e) { ((MessageDisplay)obj).Message = (Message)e.NewValue; } 
+3
source

All Articles