Converting WPF Datatemplates Using x: Type in Silverlight
I have a WPF application that uses x: type when working with datatemplates. This doesn't work out of the box in Silverlight, but I remember seeing something on the googlegroup a while back where they talked about Silverlight extensions and how it could be used.
If anyone knows what I am talking about or knows how I can reuse my datatemplates in silverlight and you have a nice sample of code that you would make my day.
/ Johan
I had the same problem a few days ago ... and found a solution ... I'm not very proud of it, but it works. create data table and add all possible custom controls there
<DataTemplate x:Key="WorkspaceItemTemplate">
<Grid>
<View:TreeView Visibility="{Binding Converter={StaticResource ViewVisibilityConverter}, ConverterParameter=TreeView}" />
<View:GridView Visibility="{Binding Converter={StaticResource ViewVisibilityConverter}, ConverterParameter=GridView}" />
<View:DataView Visibility="{Binding Converter={StaticResource ViewVisibilityConverter}, ConverterParameter=DataView}" />
</Grid>
</DataTemplate>
and create a converter that changes visibility based on type
public class ViewVisibilityConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (((ViewModelBase)value).DisplayName.Equals((string)parameter))
return Visibility.Visible;
return Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
source to share
Finally, this was fixed in Silverlight 5. Now you can write a thing like this:
<DataTemplate DataType="loc:MyType">
<TextBlock Text="My template" />
</DataTemplate>
You can put this in the resource dictionary without specifying x: Key.
Note that Silverlight does not support the x: Type attribute, so you only need to specify the type name without the markup extension, as Muad'Dib mentions (although his suggestion didn't actually work when he wrote it back in 2009 - Silverlight DataTemplate even didn't have a DataType property until December 2011).
source to share
in silverlight, you leave the x: Type and drop the curly braces ... like this ....
<Style TargetType="local:TemplatedControl">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:TemplatedControl">
<StackPanel x:Name="Panel" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
source to share