How to get Image and text from RSS file in WP7? - c#

I am trying to get RSS text with its Image but image couldn't show i would view model for getting image and use simple RSS technique to get image would you tell me how to get both image and text.......
Here is my XAML code:
<ListBox Name="lstRSS" ItemsSource="{Binding FeedItems}" DataContext="{StaticResource MainViewModel}" FontSize="30" Grid.Row="1">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Height="700">
<TextBlock Text="{Binding Path=Title}"></TextBlock>
<UserControls:Loader Width="100" Height="100" />
<Image Source="{Binding Link}" Width="450" Height="350" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>

You cannot bind to a URL in that way as a String/Uri is not a valid value for the Image.Source property. If a constant URL is set in xaml then the image will be shown correctly as the compiler generated code takes the URL and converts it to a BitmapSource.
To bind an image URL in that fashion you will need a converter. The converter can take the URL and convert it to a BitmapImage:
public class UriToImageConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
// This could be extended to accept a Uri as well
string url = value as string;
if (!string.IsNullOrEmpty(url))
{
return new BitmapImage(new Uri(url, UriKind.RelativeOrAbsolute));
}
else
{
return null;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
You then need to add an instance of this class to the apps resources (in app.xaml or in the page xaml):
<local:UriToImageConverter x:Key="ImageConverter"/>
You can then set the binding like this:
<Image Source="{Binding Link, Converter={StaticResource ImageConverter}}" />

Related

Using a IConverter to deal with {NewItemPlaceholder} in WPF / XAML / MVVM

Here is my DataTemplate:
<UserControl.Resources>
<converter:PlaceholderConverter x:Key="_placeholderConverter"/>
<!-- Data(Display)Template for data objects of x:Type Customer-->
<DataTemplate DataType="{x:Type model:Customer}">
<!-- Customer Properties will be vertically stacked -->
<ContentControl >
<StackPanel>
<TextBlock Text="{Binding FirstName}"/>
<TextBlock Text="{Binding LastName}"/>
<TextBlock Text="{Binding Phone}"/>
</StackPanel>
</ContentControl>
</DataTemplate>
<UserControl.Resources>
And the two different 'container's:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="25"/>
<RowDefinition Height="100"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Button Grid.Row="0"
Content="Delete"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Width="75"
Command="{Binding DeleteCommand}"/>
<DataGrid Grid.Row="1"
ItemsSource="{Binding Customers}"
SelectedItem="{Binding SelectedCustomer}"
AutoGenerateColumns="True"/>
<ListBox
Grid.Row="2"
ItemsSource="{Binding Customers, Mode=OneWay}"/>
</Grid>
And the app:
How to remove the {NewItemPlaceholder}? [Done, solution below].
How to prevent the binding error that mention "{NewItemPlaceholder}" when clicking in one of the empty rows in the table above intending on adding a new row (I can still add rows).
The errors:
...Cannot convert '{NewItemPlaceholder}' from type 'NamedObject' to type 'CustomerExample.Model.Customer'...
...ConvertBack cannot convert value '{NewItemPlaceholder}' (type 'NamedObject'). BindingExpression:Path=SelectedCustomer; DataItem='CustomerViewModel'...
I can write an IConverter implementation, but how to tie it in to the XAML?
thanks in advance :-)
Here is the implementation of the IConverter:
public class PlaceholderConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value != null && value.ToString() == "{NewItemPlaceholder}")
return DependencyProperty.UnsetValue;
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
and to bind to individual items, the XAML goes something like:
<TextBlock Text="{Binding Name, Converter={StaticResource PlaceholderConverter}}"/>
But I think I need to add it 'globally' to the data collection elements, not to where individual properties are being bound.
You don't need a Binding Converter. Instead, bind the ListBox to a CollectionViewSource that wraps the Custumers collection. The CollectionViewSource skips the NewItemPlaceholder element from the source collection.
<UserControl.Resources>
...
<CollectionViewSource x:Key="CustomersCVS" Source="{Binding Customers}"/>
</UserControl.Resources>
...
<ListBox ItemsSource="{Binding Source={StaticResource CustomersCVS}}"/>
You also don't need a Converter for the SelectedItem Binding. Just set the Binding's TargetNullValue property:
<DataGrid SelectedItem="{Binding SelectedCustomer,
TargetNullValue={x:Static CollectionView.NewItemPlaceholder}}" .../>
Even though the accepted answer is correct for the OP's question I needed a more general approach to prevent the error and still allow users to add rows. As I used this ValueConverter for many different object types I used reflection to determine the target type's constructor and just returned a new object of that type.
public class IgnoreNewItemPlaceHolderConverter : IValueConverter
{
private const string NewItemPlaceholderName = "{NewItemPlaceholder}";
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == DependencyProperty.UnsetValue)
return DependencyProperty.UnsetValue;
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null && value.ToString() == NewItemPlaceholderName)
{
var ctors = targetType.GetConstructors();
// invoke the first public constructor with no parameters.
return ctors[0].Invoke(new object[] { });
}
return value;
}
}

C# - WPF - Binding a List<int> to be printed in a StatusBar?

I have the following in xaml:
<StatusBarItem Content="{Binding CorrectGuesses}" Height="30" VerticalAlignment="Top" HorizontalContentAlignment="Center" />
Here, CorrectGuesses is a List<int>. I'd like the code to output the actual numbers in the list to the statusbar, but right now it only shows (Collection). What do I need to do so that the StatusBarItem's Content will be the items in the list? Thank you!
Add a Converter , so that it prints all the numbers.
namespace AppConverters
public class List2StringConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
List<int> listNumbers = value as List<int>;
// separator : , - / ... or white space
return string.join("separator",listNumbers);
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
// To Do
}
}
in your xaml page add this line to your window tag as schema:
xmlns:app="clr-namespace:AppConverters"
also add :
<Window.Resources>
<app:List2StringConverter x:Key="L2StringConverter"/>
</Window.Resources>
then use it as follows :
<StatusBarItem Content="{Binding CorrectGuesses,Converter={StaticResource L2StringConverter}}" Height="30" VerticalAlignment="Top" HorizontalContentAlignment="Center" />
<StatusBarItem Height="30" VerticalAlignment="Top" HorizontalContentAlignment="Center">
<ItemsControl ItemsSource="{Binding CorrectGuesses}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StatusBarItem>

Binding base64 String Image into List view Stored in SQLite Database in windows phone 8.1

I have converted Image to base64 string and saved it in SQLite database as public string ProfileImage { get; set; }
I want to bind image into a List view as I did binding Name and Address.
XAML
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Border Background="{ThemeResource ListViewItemPlaceholderBackgroundThemeBrush}" Margin="0,10,0,0" Grid.Column="0" HorizontalAlignment="Left">
<Image x:Name="proImg" Source="{Binding ProfileImage}" Stretch="UniformToFill" Height="79" Width="79"/>
</Border>
<StackPanel Grid.Column="1" Margin="14.5,0,0,0">
<TextBlock Margin="5,0,0,0" Grid.Row="0" x:Name="NameTxt" TextWrapping="Wrap" Text="{Binding Name}" FontSize="32" Foreground="White" Style="{ThemeResource ListViewItemTextBlockStyle}"/>
<TextBlock Margin="5,0,0,0" Grid.Row="1" x:Name="PhoneTxt" TextWrapping="Wrap" Foreground="White" FontSize="20" Text="{Binding Address}" />
</StackPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
Code I used to convert base64 String to Image in other Places
public static BitmapImage Base64StringToBitmap(string source)
{
var ims = new InMemoryRandomAccessStream();
var bytes = Convert.FromBase64String(source);
var dataWriter = new DataWriter(ims);
dataWriter.WriteBytes(bytes);
dataWriter.StoreAsync();
ims.Seek(0);
var img = new BitmapImage();
img.SetSource(ims);
return img;
}
Is it possible to bind image source similar way to this
Source="{Binding Base64StringToBitmap(ProfileImage)}"
You cannot call method in Xaml Binding like this. You need to convert it by implementing IValueConverter and then bind it. You should use a ValueConverter like this.
public class StringToBitmapConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value != null)
{
string source = value.ToString();
var ims = new InMemoryRandomAccessStream();
var bytes = Convert.FromBase64String(source);
var dataWriter = new DataWriter(ims);
dataWriter.WriteBytes(bytes);
dataWriter.StoreAsync();
ims.Seek(0);
var img = new BitmapImage();
img.SetSource(ims);
return img;
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
and use this converter in Xaml like this
xmlns:MyConverter="using:Your converter namespace path"
<Page.Resources>
<MyConverter:StringToBitmapConverter x:Key="ImageShow"/>
</Page.Resources>
<Image x:Name="proImg" Source="{Binding ProfileImage,Converter={StaticResource ImageShow}}" Stretch="Fill" Height="60" Width="60"/>
You should add a XAML IValueConverter to bind the image in your scenario.Converter will do the conversion of Base64String to Bitmap Image.
Add a class with interface IValueConverter as like below.
public class PictureConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value == null)
{
return null;
}
string item = value.ToString();
BitmapImage objBitmapImage = new BitmapImage();
objBitmapImage = NewViewModel.Base64StringToBitmap(item);
return objBitmapImage;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
Now define a key to this converter either in Resource dictionary or in Page
<Page.Resources>
<local:PictureConverter x:Key="PictureConverter"/>
</Page.Resources>
Then bind your key in XAML
<Image x:Name="proImg" Source="{Binding ProfileImage,Converter={StaticResource PictureConverter}}" Stretch="UniformToFill" Height="79" Width="79"/>
Hope now image is being displayed.

WPF Binding to converter for an Image (Bitmap) not showing

I am having issues with an image not showing in a WPF control using a Converter to create the image from a local directory. Any direction on what I am doing wrong would be appreciated.
XAML
<UserControl x:Class="Coms.Views.ImageDetailView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:c="clr-namespace:Coms.Converter"
mc:Ignorable="d"
d:DesignHeight="100" d:DesignWidth="300" Background="Wheat">
<Control.Resources>
<c:ImageDetailConverter x:Key="converter" />
</Control.Resources>
<ListBox ItemsSource="{Binding icList}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Auto">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="200"/>
</Grid.ColumnDefinitions>
<Image Name="imgBox" Width="auto" Height="auto" Grid.Column="0" Source="{Binding Converter={StaticResource converter}}" />
<TextBlock Name="txtBlock2" Grid.Column="1" Text="{Binding coordinates}"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
class
public class ImageDetail
{
public string fileName { get; set; }
public string coordinates { get; set; }
}
Converter
public class ImageDetailConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
IRuntimeConfigurations configs = ServiceLocator.Current.GetInstance<IRuntimeConfigurations>();
return new Bitmap(Image.FromFile(Path.Combine(configs.rootImagePath, ((IImageDetail)value).fileName)));
}
}
Your converter returns a System.Drawing.Bitmap, which is WinForms, not WPF.
It should return a WPF ImageSource (e.g. a BitmapImage) instead:
public object Convert(
object value, Type targetType, object parameter, CultureInfo culture)
{
var imageDetail = (ImageDetail)value;
var configs = ServiceLocator.Current.GetInstance<IRuntimeConfigurations>();
var path = Path.Combine(configs.rootImagePath, imageDetail.fileName);
var uri = new Uri(path, UriKind.RelativeOrAbsolute);
return new BitmapImage(uri);
}
Note also that WPF provides built-in type conversion from Uri and string (containing a valid URI) to ImageSource, so that your converter could also return the uri or path value.

How to Convert Image Using Ivalueconverter and Bind it in Listview

I want to Bind the VarBinary(Max) using Ivaluconverter But Problem is that I have a error which is
Error 1 The tag 'ImageDataConverter' does not exist in XML namespace
'clr-namespace:UI'. Line 7 Position 10. C:\Documents and
Settings\Muhammad Yaqoob\My Documents\Visual Studio
2008\Projects\BLL\UI\Pics.xaml 7 10 UI
I Retrieve Image like this
DataClasses1DataContext dt = new DataClasses1DataContext();
var query = from prod in dt.Students
where (prod.StudentID == 100)
select new
{
prod.LastName,
prod.StudentID,
prod.MyImage
};
this.listView1.ItemsSource = query;
Then i use the Ivalconverter to Convert the Image From VarBinary to the Image as
public class ImageDataConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
return value;
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
#region IValueConverter Members
object IValueConverter.Convert(
object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
object IValueConverter.ConvertBack(
object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
And my .Xmal file is like that
xmlns:local="clr-namespace:UI" /// i have problem at here can't find the essembly info or Resours file
Title="Pics" Height="408" Width="406" xmlns:my="http://schemas.microsoft.com/wpf/2008/toolkit" Loaded="Window_Loaded">
<Window.Resources>
<local:ImageDataConverter x:Key="imageConverter"/> // ImageDataConverter cant be locat at here
</Window.Resources>
<ListView Name="listView1" VerticalContentAlignment="Stretch" HorizontalContentAlignment="Stretch" Height="263">
<ListView.ItemTemplate>
<DataTemplate>
<Border Margin="5" BorderThickness="1" BorderBrush="SlateGray" CornerRadius="4">
<Grid Margin="3">
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock FontWeight="Bold" Text="{Binding Path=Name}"></TextBlock>
<TextBlock Grid.Row="1" Text="{Binding Path=ListPrice}"></TextBlock>
<Image Grid.Row="2" Source="{Binding Path=ThumbNailPhoto , Converter={StaticResource imageConverter}}"></Image>
</Grid>
</Border>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
i cant know how to solve this problem the problem is that my resourse propertie of ImageDataconvert is not converting and also essembly is not found for the IN the UI project yes my project is in tree tier and my resourse sitting is in UI project

Categories