I'm attempting to databind a custom control in Silverlight 3 and I'm getting strange problems with it.
My xaml for the user control is this:
<UserControl x:Class="StronicoMain.GenericSmallIcon"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300" >
<Canvas x:Name="canGSI">
</Canvas>
</UserControl>
The codebehind for the user control is this
private string _EntityTypeID;
public string EntityTypeID
{
get
{
return _EntityTypeID;
}
set
{
_EntityTypeID = value;
}
}
public GenericSmallIcon()
{
InitializeComponent();
Loaded += new RoutedEventHandler(Page_Loaded);
}
public void Page_Loaded(object sender, RoutedEventArgs e)
{
icoMale icoMale = new icoMale();
icoFemale icoFem = new icoFemale();
if (EntityTypeID == null)
{
canGSI.Children.Add(icoMale);
}
else if (EntityTypeID == "1")
{
canGSI.Children.Add(icoMale);
}
else if (EntityTypeID == "2")
{
canGSI.Children.Add(icoFem);
}
else
{
canGSI.Children.Add(icoMale);
}
}
I'm calling it from the DataGridSelection Adapter (taken from the Microsoft Toolkit example page for AutoCompleteBox-Datagrid version) - the relevant portion looks like this:
<Stron:DataGridSelectionAdapter x:Name="SelectionAdapter" AutoGenerateColumns="False" IsReadOnly="False">
<Stron:DataGridSelectionAdapter.Columns>
<data:DataGridTemplateColumn>
<data:DataGridTemplateColumn.CellTemplate>
<DataTemplate><Stron:GenericSmallIcon EntityTypeID="{Binding EntityTypeID}"></Stron:GenericSmallIcon></DataTemplate>
</data:DataGridTemplateColumn.CellTemplate>
</data:DataGridTemplateColumn>
<data:DataGridTextColumn Header="Contact Name" FontWeight="Bold" Foreground="#CC000000" Binding="{Binding EntityName}" />
<data:DataGridTextColumn Header="Tags" Binding="{Binding EntityTags}" />
</Stron:DataGridSelectionAdapter.Columns>
</Stron:DataGridSelectionAdapter>
I run the code, and I get the error "ManagedRuntimeError #4004" - if I try to use the custom control while manually setting the databinding it works just fine, if I try to rely on the values that are being databound I get the error. How can I create a custom databound event on a custom control? I think that is the problem, that the page is loading before the values are passed to it.
Thanks everyone.
~Steve
Update, here is the working, changed code as per the accepted answer
public static readonly DependencyProperty EntityTypeIDProperty = DependencyProperty.Register("EntityTypeID", typeof(string), typeof(GenericSmallIcon), new PropertyMetadata(new PropertyChangedCallback(GenericSmallIcon.OnEntityTypeIDPropertyChanged)));
public string EntityTypeID
{
get { return (string)GetValue(EntityTypeIDProperty); }
set { SetValue(EntityTypeIDProperty, value); }
}
private static void OnEntityTypeIDPropertyChanged(
DependencyObject d, DependencyPropertyChangedEventArgs e)
{
GenericSmallIcon control = d as GenericSmallIcon;
string b = (string)e.NewValue;
}