the label does not show the photo from the class - WPF - c#

please give me a hand! i have one simple WPF project, which it doesn't show the image. i have been struggling with it since one week, can not find my mistake! i looked a lot the solutions on this website, but still did not help me!
C# Code from Display Window
public partial class Boatdetails : Window
{
//public Boatdetails()
public Boatdetails(Object boot)
{
InitializeComponent();
if (boot is Ruderboot)
{
modell.Content = ((Ruderboot)boot).Modell;
plaetze.Content = ((Ruderboot)boot).Plaetze;
preis.Content = ((Ruderboot)boot).Preis;
bild.Content = ((Ruderboot)boot).Image;
HoheStack.Visibility = Visibility.Hidden;
MoroStack.Visibility = Visibility.Hidden;
}
else if (boot is Segelboote)
{
modell.Content = ((Segelboote)boot).Modell;
plaetze.Content = ((Segelboote)boot).Plaetze;
preis.Content = ((Segelboote)boot).Preis;
bild.Content = ((Segelboote)boot).Image;
hohe.Content = ((Segelboote)boot).Height;
HoheStack.Visibility = Visibility.Visible;
MoroStack.Visibility = Visibility.Hidden;
}
else
{
modell.Content = ((Motorboot)boot).Modell;
plaetze.Content = ((Motorboot)boot).Plaetze;
preis.Content = ((Motorboot)boot).Preis;
bild.Content = ((Motorboot)boot).Image;
motorModel.Content = ((Motorboot)boot).MotorModel;
motoLeistung.Content = ((Motorboot)boot).EnginePerformence;
HoheStack.Visibility = Visibility.Hidden;
MoroStack.Visibility = Visibility.Visible;
}
BitmapImage jpg = new BitmapImage(new Uri(((Boote)boot).Image, UriKind.Relative)); //Bild setzten, relativ im ordner images
Image img = new Image();
img.Source = jpg;
bild.Content = img;
}
private void showDetails(object detail)
{
spDetail.Height = 27;
lblDetails.Visibility = System.Windows.Visibility.Visible;
details.Visibility = System.Windows.Visibility.Visible;
}
}
and XML Window Code
<StackPanel>
<StackPanel Orientation="Horizontal">
<Label Content="Bild:" Width="100"/>
<Label x:Name="bild" Width="200" Height="200"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<Label Content="Modell:" Width="100"/>
<Label x:Name="modell" />
</StackPanel>
<StackPanel Orientation="Horizontal">
<Label Content="Plätze:" Width="100"/>
<Label x:Name="plaetze" />
</StackPanel>
<StackPanel x:Name="spDetail" Orientation="Horizontal" Height="0">
<Label x:Name="lblDetails" Content="Details:" Width="100" Visibility="Hidden"/>
<Label x:Name="details" Visibility="Hidden"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<Label Content="Preis:" Width="100"/>
<Label x:Name="preis" />
</StackPanel>
<StackPanel Orientation="Horizontal"
Name="HoheStack"
Visibility="Visible">
<Label Content="Hohe:" Width="100"/>
<Label x:Name="hohe" />
</StackPanel>
<StackPanel x:Name="MoroStack"
Visibility="Visible">
<StackPanel Orientation="Horizontal"
Visibility="Visible">
<Label Content="Moto Modell:" Width="100"/>
<Label x:Name="motorModel" />
</StackPanel>
<StackPanel Orientation="Horizontal">
<Label Content="Leistung" Width="100"/>
<Label x:Name="motoLeistung" />
</StackPanel>
</StackPanel>
</StackPanel>
this is how i have added object into the class:
rl.Add(new Ruderboot() { Modell = "XLight", Plaetze = 1, Preis = 3400, Image = "./Images/ruderboot1.jpg" });
and my class
public class Boote
{
public string Modell { get; set; }
public sbyte Plaetze { get; set; }
public float Preis { get; set; }
public string Image { get; set; }
public override string ToString()
{
return Modell + ": "+ Preis+"€";
}
}

Set the Build Action of the image files in your project to Resource (Solution Explorer -> Context Menu -> Properties) and load them by Resource File Pack URIs like
Image = "pack://application:,,,/Images/ruderboot1.jpg"
Besides that, you should use data binding. Assign the passed boat object to the DataContext of the Window:
public Boatdetails(Object boot)
{
DataContext = boot;
InitializeComponent();
}
In XAML, just write expressions like
<TextBlock Text="{Binding Modell}"/>
<Image Source="{Binding Image}"/>
where in the latter case the conversion from string to ImageSource is performed automatically by the framework.
You could use a single ContentControl with different DataTemplates for different boat types, like
<Window x:Class="BoatdetailsTest.Boatdetails" ...>
<Window.Resources>
<DataTemplate DataType="{x:Type local:Ruderboot}">
<StackPanel>
<!-- elements for Ruderboot -->
</StackPanel>
</DataTemplate>
<DataTemplate DataType="{x:Type local:Segelboot}">
<StackPanel>
<!-- elements for Segelboot -->
</StackPanel>
</DataTemplate>
</Window.Resources>
<Grid>
<ContentControl Content="{Binding}"/>
</Grid>
</Window>

Related

Xamarin Forms - Translating drawer menu items at runtime

I'm following the exelent tutorial (Link) on Multilingual in Xamarin.Forms
Everything is working well but I have one issue.
In my application I'm using Navigation drawer by Syncfusion as I'm generating the menu Items in a ListView as seen below.
DrawerPage.xaml
<ListView x:Name="listView"
SelectionMode="Single"
RowHeight="70"
ItemSelected="listView_ItemSelected"
SeparatorColor="Transparent">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Margin="32,10,0,0"
VerticalOptions="Center" >
<Grid RowDefinitions="1*, Auto">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<Label Grid.Row="0"
Grid.Column="0"
HorizontalTextAlignment="Start"
HorizontalOptions="Start"
FontSize="25"
FontFamily="Material-Outlined"
Style="{StaticResource IconLabelStyle}"
Text="{Binding Icon}" />
<Label Grid.Row="0"
Grid.Column="1"
HorizontalTextAlignment="Start"
HorizontalOptions="Start"
Margin="10,0,0,0"
Text="{Binding Name}"
FontSize="16"/>
</Grid>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
DrawerPage.cs
private static string MAP = Lang.ResourceManager.GetString("Map");
private static string MAPICON = IconFont.ResourceManager.GetString("LocationOn");
private static string SETTINGS = Lang.ResourceManager.GetString("Settings");
private static string SETTINGSICON = IconFont.ResourceManager.GetString("Settings");
public partial class DrawerPage : ContentPage {
drawerNavItems();
}
private void drawerNavItems()
{
List<MenuItem> itemList = new List<MenuItem>();
itemList.Add(new MenuItem { Icon = MAPICON, Name = MAP });
itemList.Add(new MenuItem { Icon = SETTINGSICON, Name = SETTINGS });
listView.ItemsSource = itemList;
}
The issue I'm having is that I don't understand how I'm supposed to use the helper class in the tutorial link above to translate the drawer menu items.
In Xaml we can just translate the strings like this
Text="{helpers:Translate Support}"
But how do I do the same in the code Behind ?

My Print PDF Doesn't Show the Binded Data of the Original Window - C# MVVM

I am trying to print my window (Print Preview) using MVVM architecture. So far I was able to get the controls of the window into the print. But it doesn't show the data bindings.
This is my PrintPreview.xaml code
<ScrollViewer VerticalScrollBarVisibility="Auto">
<!--Main Grid-->
<Grid x:Name="MainGrid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2.5*"/>
<ColumnDefinition Width="3*"/>
<ColumnDefinition Width="2.5*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height ="1.5*"/>
<RowDefinition Height ="1.7*"/>
<RowDefinition Height ="5*" MinHeight="200"/>
<RowDefinition Height ="7*" MinHeight="200"/>
<RowDefinition Height ="6*" MinHeight="100"/>
<RowDefinition Height ="2*"/>
</Grid.RowDefinitions>
<Grid Grid.RowSpan="2" Grid.ColumnSpan="3" Background="#9dc6a7"/>
<!--Patient Id block-->
<StackPanel Grid.ColumnSpan="2" Style="{StaticResource StackpanelStyle}">
<Label FontSize="16" FontWeight="Bold" Foreground="White">
Patient ID :
</Label>
<Label FontSize="16" Foreground="White" Margin="5,0,0,0" Content="{Binding Path=PatientID}"/>
</StackPanel>
<!--Date block-->
<StackPanel Grid.ColumnSpan="3" Style="{StaticResource StackpanelStyle}" HorizontalAlignment="Right">
<Label FontSize="16" FontWeight="Bold" Foreground="White">
Date :
</Label>
<Label Name="date_time" FontSize="16" Foreground="White" Margin="5,0" Content="{Binding Path=CurrentDate}"/>
</StackPanel>
<!--Title block-->
<TextBlock Grid.Row="1" Grid.ColumnSpan="3" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="20" FontWeight="Bold" TextDecorations="Underline" Foreground="White">
Patient Registration Information
</TextBlock>
<!--Sub grid 1-->
<Grid Grid.Row="2" Grid.ColumnSpan="3" HorizontalAlignment="Center" VerticalAlignment="Stretch" Margin="25,10,25,10">
<!--User's image View and name-->
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" Orientation="Vertical">
<Ellipse Width="150" Height="150">
<Ellipse.Fill>
<ImageBrush x:Name="ImageViewer2" ImageSource="{Binding Path=PatientImageSource}"/>
</Ellipse.Fill>
</Ellipse>
<StackPanel HorizontalAlignment="Left" Orientation="Horizontal" Margin="0,10">
<Label Style="{StaticResource LabelStyles}" Margin="0">Patient Name :</Label>
<TextBlock x:Name="ViewName" Style="{StaticResource TextBlockStyle}" Text="{Binding Path = PatientName}"/>
</StackPanel>
</StackPanel>
</Grid>
<!--Sub grid 2-->
<GroupBox Grid.Row="3" Grid.ColumnSpan="3" HorizontalAlignment="Stretch" VerticalAlignment="Center" Margin="25,-35,25,0">
<GroupBox.Header>
<TextBlock Style="{StaticResource TextBlockStyleControl}">Patient Personal Information</TextBlock>
</GroupBox.Header>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="500*"/>
<ColumnDefinition Width="500*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="5*"/>
<RowDefinition Height="3*" MaxHeight="80"/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Grid.Column="0" Orientation="Vertical" Margin="10,5">
<Label Style="{StaticResource PreviewLabelStyles}" >Address :</Label>
<TextBlock x:Name="ViewANum" Style="{StaticResource TextBlockStyle}" Text="{Binding Path = PatientAddress.Number}"/>
<TextBlock x:Name="ViewAStrt" Style="{StaticResource TextBlockStyle}" Text="{Binding Path = PatientAddress.Street}"/>
<TextBlock x:Name="ViewACity" Style="{StaticResource TextBlockStyle}" Text="{Binding Path = PatientAddress.City}"/>
</StackPanel>
<StackPanel Grid.Row="0" Grid.Column="1" Orientation="Vertical" Margin="50,5,10,10">
<Label Style="{StaticResource PreviewLabelStyles}">Gender :</Label>
<TextBlock x:Name="ViewGender" Style="{StaticResource TextBlockStyle}" Text="{Binding Path = PatientGender}"/>
</StackPanel>
<StackPanel Grid.Row="1" Grid.Column="0" Orientation="Vertical" Margin="10,5">
<Label Style="{StaticResource PreviewLabelStyles}">Date of Birth :</Label>
<TextBlock x:Name="ViewDob" Style="{StaticResource TextBlockStyle}" Text="{Binding Path = PatientDateOfBirth}"/>
</StackPanel>
<StackPanel Grid.Row="1" Grid.Column="1" Orientation="Vertical" Margin="50,5,10,5">
<Label Style="{StaticResource PreviewLabelStyles}">Age :</Label>
<TextBlock x:Name="ViewAge" Style="{StaticResource TextBlockStyle}" Text="{Binding Path = PatientAge}"/>
</StackPanel>
</Grid>
</GroupBox>
<!--Sub grid 3-->
<GroupBox Grid.Row="4" Grid.ColumnSpan="3" HorizontalAlignment="Stretch" VerticalAlignment="Center" Margin="25,-25,25,0">
<GroupBox.Header>
<TextBlock Style="{StaticResource TextBlockStyleControl}">Patient Medical Information</TextBlock>
</GroupBox.Header>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="500*"/>
<ColumnDefinition Width="500*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="3*"/>
<RowDefinition Height="3*" />
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Grid.Column="0" Orientation="Vertical" Margin="10,5">
<Label Style="{StaticResource PreviewLabelStyles}">Department :</Label>
<TextBlock x:Name="ViewDepartment" Style="{StaticResource TextBlockStyle}" Text="{Binding Path=PatientDepartment}"/>
</StackPanel>
<StackPanel Grid.Row="0" Grid.Column="1" Orientation="Vertical" Margin="50,5,10,0">
<Label Style="{StaticResource PreviewLabelStyles}">Ward :</Label>
<TextBlock x:Name="ViewWard" Style="{StaticResource TextBlockStyle}" Text="{Binding Path=PatientWard}"/>
</StackPanel>
<StackPanel Grid.Row="1" Grid.Column="0" Orientation="Vertical" Margin="10,5,10,10">
<Label Style="{StaticResource PreviewLabelStyles}">Doctor in Charge :</Label>
<TextBlock x:Name="ViewDoc" Style="{StaticResource TextBlockStyle}" Text="{Binding Path=PatientDotorcInCharge}"/>
</StackPanel>
</Grid>
</GroupBox>
<Button Grid.Row="5" Grid.Column="2" Style="{StaticResource ButtonStyle}" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="20,7,26,0" Content="Print Content" Command="{Binding Path=PrintCommand}"/>
</Grid>
</ScrollViewer>
This is my PrintPreview ViewModel code,
class PrintPreviewViewModel
{
#region Data Members
private IWindowService m_windowService;
#endregion
#region Constructors
public PrintPreviewViewModel(PatientRecordDetailsModel patient)
{
string id = patient.PatientId;
PatientID = id.PadRight(6).Substring(0, 6);
PatientName = patient.PatientName;
PatientAddress = patient.PatientAddress;
PatientGender = patient.PatientGender;
PatientDateOfBirth = patient.PatientDateOfBirth.ToShortDateString();
PatientAge = patient.PatientAge;
PatientImageSource = patient.PatientImageSource;
PatientDepartment = patient.PatientDepartment;
PatientWard = patient.PatientWard;
PatientDotorcInCharge = patient.PatientDoctorInCharge;
m_windowService = new WindowService();
}
#endregion
#region Properties
public string PatientID { get; set; }
public string PatientName { get; set; }
public PatientAddress PatientAddress { get; set; }
public string PatientGender { get; set; }
public string PatientDateOfBirth { get; set; }
public int PatientAge { get; set; }
public ImageSource PatientImageSource { get; set; }
public string PatientDepartment { get; set; }
public string PatientWard { get; set; }
public string PatientDotorcInCharge { get; set; }
#endregion
#region <PrintPreview> Members
public string CurrentDate => m_windowService.GetCurrentDate();
#endregion
#region Properties : Commands
public ICommand PrintCommand
{
get => new PatientRecordDetailsCommands(param => OnPrintCommandExecute(), param => OnPrintCommandCanExecute());
}
#endregion
#region Handlers : Commands
private void OnPrintCommandExecute()
{
m_windowService.PrintWindow();
}
private bool OnPrintCommandCanExecute()
{
return true;
}
#endregion
}
}
As you can see I am opening the printPreview Window from another window through a service class. The patient object is being send through that. Also the implementation of print button command is also defined in the same service class. I used this approach to reduce the MVVM violations.
This is my Service class
class WindowService : IWindowService
{
public void CreateWindow(PatientRecordDetailsModel patient)
{
PrintPreview printPreview = new PrintPreview();
printPreview.DataContext = new PrintPreviewViewModel(patient);
printPreview.Show();
}
public string GetCurrentDate()
{
DateTime dateTime = DateTime.Now;
string date = dateTime.ToString("d");
string time = dateTime.ToString("T");
string Date_Time = date + " " + time;
return Date_Time;
}
public void PrintWindow()
{
PrintPreview printPreview = new PrintPreview();
PrintDialog printDlg = new PrintDialog();
PrintQueue ReceiptPrinter = new LocalPrintServer().GetPrintQueue("Microsoft Print To PDF");
PrintCapabilities PC = ReceiptPrinter.GetPrintCapabilities();
printDlg.PrintQueue = ReceiptPrinter;
printPreview.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
Size PreGridSize = printPreview.DesiredSize;
double Scale = Math.Min(PC.PageImageableArea.ExtentWidth / PreGridSize.Width, PC.PageImageableArea.ExtentHeight / PreGridSize.Height);
printPreview.LayoutTransform = new System.Windows.Media.ScaleTransform(Scale, Scale);
Size PaperSize = new Size(PC.PageImageableArea.ExtentWidth, Math.Min(PC.PageImageableArea.ExtentHeight, PreGridSize.Height));
printPreview.Measure(PaperSize);
Point ptGrid = new Point(PC.PageImageableArea.OriginWidth, PC.PageImageableArea.OriginHeight);
printPreview.Arrange(new Rect(ptGrid, PaperSize));
Application.Current.Dispatcher.BeginInvoke(
new Action(delegate () { printDlg.PrintVisual(printPreview.MainGrid, "PrintPreview"); }),
DispatcherPriority.Send);
}
}
I tried assigning the patient object to the datacontext inside the PrintWindow(), but it returns a null object.
This is the original printPreview Window
This is how the print looks like
So I guess there should be a proper way of doing this.
Your problem is that you're not assigning the DataContext inside your PrintWindow function.
let's take a look
public void PrintWindow()
{
here we create a new printpreview
PrintPreview printPreview = new PrintPreview();
PrintDialog printDlg = new PrintDialog();
PrintQueue ReceiptPrinter = new LocalPrintServer().GetPrintQueue("Microsoft Print To PDF");
PrintCapabilities PC = ReceiptPrinter.GetPrintCapabilities();
printDlg.PrintQueue = ReceiptPrinter;
printPreview.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
Size PreGridSize = printPreview.DesiredSize;
double Scale = Math.Min(PC.PageImageableArea.ExtentWidth / PreGridSize.Width, PC.PageImageableArea.ExtentHeight / PreGridSize.Height);
printPreview.LayoutTransform = new System.Windows.Media.ScaleTransform(Scale, Scale);
Size PaperSize = new Size(PC.PageImageableArea.ExtentWidth, Math.Min(PC.PageImageableArea.ExtentHeight, PreGridSize.Height));
printPreview.Measure(PaperSize);
Point ptGrid = new Point(PC.PageImageableArea.OriginWidth, PC.PageImageableArea.OriginHeight);
printPreview.Arrange(new Rect(ptGrid, PaperSize));
Application.Current.Dispatcher.BeginInvoke(
new Action(delegate () { printDlg.PrintVisual(printPreview.MainGrid, "PrintPreview"); }),
DispatcherPriority.Send);
}
as you can see you don't assign the datacontext to it. Indeed the createiwndow function in which you do assign the data context is not called at all.
you can see here the print command calls the PrintWindow function instead of createwindow.
#region Properties : Commands
public ICommand PrintCommand
{
get => new PatientRecordDetailsCommands(param => OnPrintCommandExecute(), param => OnPrintCommandCanExecute());
}
#endregion
#region Handlers : Commands
private void OnPrintCommandExecute()
{
m_windowService.PrintWindow();
}
private bool OnPrintCommandCanExecute()
{
return true;
}
#endregion

ListBox Item layout in XAML/WPF

I am struggling last days to achieve following layout:
I have a ListBox with template for each Item:
Label always anchored on left side
Label always anchored on right side
Label (TextBlock) in middle with flexible size
3rd label bellow, so far this is easiest to set :)
Main problem in my example is that I can't made middle text (that can be long) to adjust, but not push suffix (red) label while I am resizing ListBox.
I hope that this layout is possible, and that I am missing something trivial.
What's interesting is that 1st example (bellow) work well "outside" listbox. Do I need somehow force realign of listbox while resizing?
Thanks for any help.
I have attached bellow 2 examples I tried (beside many other):
XAML:
<Window x:Class="WPF_Experiments.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WPF_Experiments"
mc:Ignorable="d"
Title="MainWindow" Height="400" Width="400">
<Window.Resources>
<DataTemplate x:Key="Template1">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition Width="auto" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Foreground="Blue" Background="Aqua" Content="{Binding Prefix}" />
<Label Grid.Column="1" Content="{Binding Description}" />
<Label Grid.Column="2" Foreground="Magenta" Background="Beige" Content="{Binding Suffix}" />
</Grid>
</DataTemplate>
<DataTemplate x:Key="Template2">
<DockPanel LastChildFill="True">
<Label Grid.Column="0" Foreground="Blue" Background="Aqua" Content="{Binding Prefix}" />
<Label Grid.Column="2" DockPanel.Dock="Right" Foreground="Magenta" Background="Beige" Content="{Binding Suffix}" />
<TextBlock Grid.Column="1" Text="{Binding Description}" TextTrimming="CharacterEllipsis" />
</DockPanel>
</DataTemplate>
</Window.Resources>
<StackPanel>
<ListBox Name="MyListBox"
ItemTemplate="{DynamicResource Template2}"/>
</StackPanel>
</Window>
C#:
namespace WPF_Experiments
{
class Item
{
public string Prefix { get; set; }
public string Description { get; set; }
public string Suffix { get; set; }
}
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<Item> items = new List<Item>();
items.Add(new Item() { Prefix = "001", Description = "Item 0", Suffix = "cm" });
items.Add(new Item() { Prefix = "002", Description = "This is very long item that maybe will not fit", Suffix = "in" });
items.Add(new Item() { Prefix = "003", Description = "Item 2", Suffix = "m" });
MyListBox.ItemsSource = items;
}
}
}
(Edit) One more try with StackPanel:
<DataTemplate x:Key="Template3">
<StackPanel Orientation="Horizontal">
<Label Foreground="Blue" Background="Aqua" Content="{Binding Prefix}" />
<TextBlock Text="{Binding Description}" TextTrimming="CharacterEllipsis" />
<Label Foreground="Magenta" Background="Beige" Content="{Binding Suffix}" HorizontalAlignment="Right" />
</StackPanel>
</DataTemplate>
You can achieve this by disabling horizontal scrolling for ListBox:
<ListBox Name="MyListBox" ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ItemTemplate="{DynamicResource Template2}"/>

Windowsphone textblock limitation

I have implemented textblock in Listbox ItemTemplate/data template. It is databound to "Data" which is getting read from an xml file. Everything works fine but, the text is getting trimmed in textblocks and a there ia a blank space. I know the reason and it is due to limitations in textblock. Now i tried to use, Scrollable TextBlock for WP7 from Alex Yakhnin's Blog but I am not able to understand how to implement this in my project?
C# CODE:
string XMLTagNameBody = "page";
private void ParseHeaderBody()
{
XDocument SunderGutkaXMLInstance = XDocument.Load(xmlFileToOpen);
var XMLBody = from query in SunderGutkaXMLInstance.Descendants(XMLTagNameBody)
select new BodyContentClass
{
Data = (string)query.Element("data"),
};
ListBoxDisplayContent.ItemsSource = XMLBody;
}
public class BodyContentClass
{
string book;
string data;
public string Book
{
get { return book; }
set { book = value; }
}
public string Data
{
get { return data; }
set { data = value; }
}
}
XAML Code:
<ListBox Margin="0,25,0,32"
x:Name="ListBoxDisplayContent"
FontSize="48"
HorizontalAlignment="Center">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel x:Name="ListBoxDisplayContentStackPanel"
Margin="10"
HorizontalAlignment="Center">
<TextBlock x:Name="MainContentDisplayTextBlock"
TextWrapping="Wrap"
Text="{Binding Data}"
TextAlignment="Center"
HorizontalAlignment="Center" />
<Image x:Name="dividerImage"
Stretch="Fill"
Source="/Assets/MainContentDivider.png"
Opacity="1"></Image>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Links for Alex Yakhnin's Blog/Scrollable TextBlock for WP7:
http://social.msdn.microsoft.com/Forums/windowsapps/en-US/3af9bc99-2526-49fc-b4a5-4170e12d11ab/do-textblocks-have-a-max-line-limit-if-so-how-do-i-increase-it?forum=wpdevelop
http://blogs.msdn.com/b/priozersk/archive/2010/09/08/creating-scrollable-textblock-for-wp7.aspx
You can create a custom control and than it can be added to your project like:
<StackPanel x:Name="ListBoxDisplayContentStackPanel" Margin="10"
HorizontalAlignment="Center">
<my:ScrollableTextBlock Text="{Binding Data}"
HorizontalAlignment="Left" Name="scrollableTextBlock1"
VerticalAlignment="Top" Height="618" Width="427" Margin="12,-11,0,0" />
<TextBlock x:Name="MainContentDisplayTextBlock"
TextWrapping="Wrap"
TextAlignment="Center"
HorizontalAlignment="Center" />
<Image x:Name="dividerImage"
Stretch="Fill"
Source="/Assets/MainContentDivider.png"
Opacity="1"></Image>
</StackPanel>
Where my is the namespace of your control.

Adding image to DataGrid row in Silverlight?

i am trying to create a list of users in Silverlight in which i want to show their Image, Name, Score etc.
I used this code to draw a datagrid so that i looks like a list :
<sdk:DataGrid Grid.Row="1" x:Name="KitchenChart" HorizontalAlignment="Center" AutoGenerateColumns="False" ItemsSource="{Binding KitchenScore}" Background="Black"
AlternatingRowBackground="Black" GridLinesVisibility="Horizontal">
<sdk:DataGrid.Columns>
<sdk:DataGridTemplateColumn Header="Image" IsReadOnly="True">
<sdk:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center" Background="Black">
<Image Source="{Binding Image}" />
</StackPanel>
</DataTemplate>
</sdk:DataGridTemplateColumn.CellTemplate>
</sdk:DataGridTemplateColumn>
<sdk:DataGridTemplateColumn Header="Name">
<sdk:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center" Background="Black">
<TextBlock Padding="5,0,5,0" Text="{Binding Name}" Foreground="White"/>
</StackPanel>
</DataTemplate>
</sdk:DataGridTemplateColumn.CellTemplate>
</sdk:DataGridTemplateColumn>
<sdk:DataGridTemplateColumn Header="Score">
<sdk:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center" Background="Black">
<TextBlock Padding="5,0,5,0" Text="{Binding Score}" Foreground="White" HorizontalAlignment="Stretch"/>
</StackPanel>
</DataTemplate>
</sdk:DataGridTemplateColumn.CellTemplate>
</sdk:DataGridTemplateColumn>
</sdk:DataGrid.Columns>
</sdk:DataGrid>
And the i used class to load dynamic data in datagrid using this as :
public class KitchenScoreClass
{
public Image Image { get; set; }
public string Name { get; set; }
public int Score { get; set; }
public KitchenScoreClass(Image Image, string Name, int Score)
{
this.Image = Image;
this.Name = Name;
this.Score = Score;
}
}
and then i created a function which loads all the data dynimically
private List<KitchenScoreClass> KitchenScore()
{
List<KitchenScoreClass> avgg = new List<KitchenScoreClass>();
avgg.Add(new KitchenScoreClass( ??? ,"kundan",10));
avgg.Add(new KitchenScoreClass( ??? , "me", 15));
avgg.Add(new KitchenScoreClass( ??? , "varun", 10));
return avgg;
}
and at last used this function to add data to datagrid KitchenChart as:
public ScoreCharts()
{
InitializeComponent();
KitchenChart.ItemsSource = KitchenScore();
}
But i don't know how should i add images ? Suppose all my images are stored in a folder Mysolution/MyImgs along with my solution folders.
How can i add Images ?
Please help
Thanks
Add the image column using "DataGridTempalteColumn." Add a cell template and create an image object to display the image in the cell. For example:
<data:DataGridTemplateColumn>
<data:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image x:Name="picture" ImageFailed="picture_ImageFailed" Width="200" Height="130" Visibility="Visible"/>
</DataTemplate>
</data:DataGridTemplateColumn.CellTemplate>
</data:DataGridTemplateColumn>
You need to read the image from disc and convert it to an Image object. You do this with an ImageSourceConverter:
ImageSourceConverter ISC = new ImageSourceConverter();
var newImage = new Image
{
Stretch = Stretch.None,
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Top
};
newImage.Source = (ImageSource)ISC.ConvertFromString(ImagePath);
NOTE: This requires that the image is downloaded to the client machine and is somewhere under the /ClientBin folder.

Categories