I'm writing a label printer in Silverlight and to show the available labels to the user I'm using a ListBox with implicit templates:
Object hierarchy
public class PrintItem { public int Id { get; set; } public decimal Price { get; set; } public string Description { get; set; } public string Barcode { get; set; } } public class NormalItem : PrintItem { } public class SaleItem : PrintItem { public decimal SalePrice { get; set; } } View Model code
PrintItems = new ObservableCollection<PrintItem>(); PrintItems.Add(new NormalItem { Id = 1, Barcode = "Barcode", Description = "Description", Price = 23.99M, }); PrintITems.Add(new SaleItem { Id = 2, Barcode = "Barcode", Description = "Description", Price = 23.99M, SalePrice = 18.99M }); XAML
<DataTemplate DataType="model:NormalItem"> <Grid Margin="10" HorizontalAlignment="Stretch"> .... </Grid> </DataTemplate> <DataTemplate DataType="model:SaleItem"> <Grid Margin="10" HorizontalAlignment="Stretch"> .... </Grid> </DataTemplate> <ListBox Margin="10" HorizontalAlignment="Center" Height="175" Width="400" ItemsSource="{Binding PrintItems}" SelectedItem="{Binding SelectedPrintItem, Mode=TwoWay}"/> This all works fine. However, the problem comes when I try to print. I previously used the example from Silverlight 5 In Action - Chapter 31, Printing which used a custom type with the ItemTemplate as a dependency property of the object being printed. This meant the following code worked:
var item = ItemTemplate.LoadContent() as FrameworkElement; Now I've changed to using Implicit Data Templates I'm struggling to work out how I can find the DataTemplate associated with the type of object being printed. Once I can get that I can use the same code to print the label as worked previously.
I've tried setting the x:Name and x:Key values on the Data Templates but that prevents the implicit styling from working for the reasons outlined in this MSDN article (I just get ViewModel.NormalItem in the ListBox).
When you set this property to the data type without specifying an x:Key, the DataTemplate gets applied automatically to data objects of that type. Note that when you do that, the x:Key is set implicitly. Therefore, if you assign this DataTemplate an x:Key value, you are overriding the implicit x:Key and the DataTemplate would not be applied automatically.
I can set the x:Uid for the Data Template, but don't really know how I can use that.
If I check the ResourceDictionary for the view the Keys are set, but the corresponding Values are null.
No comments:
Post a Comment
Send us your comment related to the topic mentioned on the blog