I'm trying to change an Image in a LongListSelector on basis of a boolean property of the DataContext of the LongListSelector. I'm using a ValueConverter in order to achieve this, and the code does reach the ValueConverter and returns a BitmapImage but this isn't visible on screen. Here's some of the relevant code:
XAML code (ItemTemplate and the ValueConverter declaration):
<local:BoolToImage x:Key="BoolImageConverter"/>
DataTemplate x:Key="itemTemplate">
<Grid Margin="0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Foreground="Black" Margin="0" FontFamily="Segoe WP Light" FontSize="29.333" VerticalAlignment="Center" Text="{Binding BeginTijdTimeOnly}" />
<TextBlock Grid.Column="1" TextWrapping="Wrap" Foreground="Black" Margin="0" FontFamily="/LimburgsLeed;component/Fonts/Fonts.zip#Champion" FontSize="48" VerticalAlignment="Center" Text="{Binding Artiest.Naam}" />
<Image x:Name="image" Grid.Column="2" Source="{Binding Path=isSaved, Converter={StaticResource BoolImageConverter}}" VerticalAlignment="Center" Margin="0, 0, -1, 0" MouseLeftButtonDown="fav_Click"/>
</Grid>
</DataTemplate>
As you can see the Image is bound to the ValueConverter and the isSaved property.
ValueConverter code:
public class BoolToImage : IValueConverter
{
public BitmapImage TrueImage = new BitmapImage();
public BitmapImage FalseImage = new BitmapImage();
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
TrueImage.UriSource = new Uri("/Images/ThumbSelected#2x.png", UriKind.RelativeOrAbsolute);
FalseImage.UriSource = new Uri("/Images/thumb.png", UriKind.RelativeOrAbsolute);
if (!(value is bool))
{
return this.FalseImage;
}
bool b = (bool)value;
if (b)
{
return this.TrueImage;
}
else
{
return this.FalseImage;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
I don't have a clue why the image isn't shown.. The ValueConverter CAN'T return null.
My god, I sure feel stupid now. This all works fine, but I set the Image files their Build Action to Embedded Resource. Changing it to content resolved the problem.
Related
My API converts many images to Byte Array and returns the Bytes, but I can't converting again to image. I intend to display in some listview all images from my API.
I tried this but I can't get any image, I was trying to get at least one.
var url = "https://appmaragogi.com.br/api/Files/Upload?Id=ChurrascariaEstreladoMar";
Byte[] imageAsBytes = client.GetByteArrayAsync(url).Result;
MemoryStream stream1 = new MemoryStream(imageAsBytes);
teste.Source = ImageSource.FromStream(() => { return stream1; });
I'd like to show all images in list view, or a way to get all images
i'm using a Image in Xaml to show the Image
You can try to make use of a Converter derived from IValueConverter which could create the image back based on the byte array.
You can refer to my thread of this:
The main code is as follows:
ByteArrayToImageSourceConverter.cs
public class ByteArrayToImageSourceConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
ImageSource retSource = null;
if (value != null)
{
byte[] imageAsBytes = (byte[])value;
var stream = new MemoryStream(imageAsBytes);
retSource = ImageSource.FromStream(() => stream);
}
return retSource;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
ImagesModel.cs
public class ImagesModel
{
// other fields
public byte[] PlayerImage { get; set; }
}
xaml(a usage example):
<ContentPage.Resources>
<ResourceDictionary>
<myformapp1:ByteArrayToImageSourceConverter x:Key="ByteArrayToImage" />
</ResourceDictionary>
</ContentPage.Resources>
<StackLayout Margin="5">
<CollectionView x:Name="collectionView"
ItemsSource="{Binding YoudataList}"> <!--changd to your dataList-->
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid Padding="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Image Grid.RowSpan="2"
x:Name="PlayerPic"
Source="{Binding PlayerImage, Converter={StaticResource ByteArrayToImage}}"
Aspect="AspectFill"
HeightRequest="60"
WidthRequest="60" />
<Label Grid.Column="1"
Text="test1"
FontAttributes="Bold" />
<Label Grid.Row="1"
Grid.Column="1"
Text="test2"
FontAttributes="Italic"
VerticalOptions="End" />
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</StackLayout>
I think that only what you need is to save it in a local file, the only thing you have to check is that the format of the image in byte array is fine
File.WriteAllBytes(nameLocalFile, imageAsBytes);
I am trying to make a scroll viewer in which scroll button is visible only when window size is too small to show all the content. I have put some button into a stackpanel which is in the scrollviewer.
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="20"/>
<RowDefinition Height="*"/>
<RowDefinition Height="20"/>
<RowDefinition/>
</Grid.RowDefinitions>
<RepeatButton x:Name="LineLeftButton"
Grid.Column="0"
Grid.Row="0"
Command="{x:Static ScrollBar.LineDownCommand}"
Background="{StaticResource uparrow}"
CommandTarget="{Binding ElementName=scrollViewer}"/>
<RepeatButton x:Name="LineRightButton"
Grid.Column="0"
Grid.Row="2"
Background="{StaticResource downarrow}"
Command="{x:Static ScrollBar.LineUpCommand}"
CommandTarget="{Binding ElementName=scrollViewer}"/>
<ScrollViewer Grid.Column="1" Grid.Row="1" x:Name="scrollViewer"
VerticalScrollBarVisibility="Hidden"
HorizontalScrollBarVisibility="Hidden">
<StackPanel Orientation="Vertical">
<Button Width="150" Height="20"/>
<Button Width="150" Height="20"/>
<Button Width="150" Height="20"/>
<Button Width="150" Height="20"/>
<Button Width="150" Height="20"/>
<Button Width="150" Height="20"/>
<Button Width="150" Height="20"/>
</StackPanel>
</ScrollViewer>
</Grid>
The scroll is working kk but how do you disable it when there are not enough element in the stack such that a scroll is not required?
You can create a converter like the following
public class MyConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is double)
{
return ((double)value < 140) ? Visibility.Visible : Visibility.Collapsed;
}
return Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
where 140 is the total height needed (you can make this parameter dynamic). Then you just need to bind the visibility of your button
<RepeatButton x:Name="LineRightButton"
Visibility="{Binding ActualHeight, Converter={StaticResource MyConv}, ElementName=scrollViewer, Mode=OneWay}"
Grid.Column="0"
Grid.Row="2"
Background="{StaticResource downarrow}"
Command="{x:Static ScrollBar.LineUpCommand}"
CommandTarget="{Binding ElementName=scrollViewer}"/>
You just need to define the converter mentioned above in your resources and it's done
EDIT Solution number 2 with Multibinding:
if you want to avoid to hardcode the total height of your button you can use a multivalueconverter and a multibinding
public class MyConverter : IMultiValueConverter
{
public object Convert(object[] value, Type targetType, object parameter, CultureInfo culture)
{
if (value[0] is double && value[1] is double)
{
return ((double)value[0] < (double)value[1]) ? Visibility.Visible : Visibility.Collapsed;
}
return Visibility.Collapsed;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
and modify your button in this way
<RepeatButton x:Name="LineRightButton"
Grid.Column="0"
Grid.Row="2"
Background="Black"
Command="{x:Static ScrollBar.LineUpCommand}"
CommandTarget="{Binding ElementName=scrollViewer}">
<RepeatButton.Visibility>
<MultiBinding Converter="{StaticResource MyConv}">
<Binding Path="ActualHeight" ElementName="scrollViewer"/>
<Binding Path="ActualHeight" ElementName="test"/>
</MultiBinding>
</RepeatButton.Visibility>
</RepeatButton>
where "test is the name of the stackpanel containing the buttons
The context is I have a Listbox that is outputting items with quite a lot of styling (more than i've put here)... I went to use a DataTemplateSelector to show either one image or another based on a condition but it was stupid to have to re-write the whole tempalte with just this one difference in it.
I have placed some pseudo code to demonstrate what i'm trying to achieve:
<ListBox Grid.Row="1"
ItemsSource="{Binding TestCases}"
BorderThickness="0"
HorizontalAlignment="Stretch"
HorizontalContentAlignment="Stretch">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"></ColumnDefinition>
<ColumnDefinition Width="auto"></ColumnDefinition>
<ColumnDefinition Width="10"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0"
Padding="0,5,0,5">
<Run Text="{Binding Class}"></Run>
</TextBlock>
<TextBlock Grid.Column="1"
Padding="5">
<Run Text="{Binding Assertions}"></Run>
</TextBlock>
if {Binding Failures} > 0 {
<Image HorizontalAlignment="Center"
Width="10"
Height="10"
Grid.Column="2"
Source="/Content/Images/Cross.png">
</Image>
}
else
{
<Image HorizontalAlignment="Center"
Width="10"
Height="10"
Grid.Column="2"
Source="/Content/Images/Tick.png">
</Image>
}
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Any ideas on how i do it?
-------------Edit------------
So far i've added the namespace of my converter class to the XAML file:
xmlns:converters="clr-namespace:Blah.Blah.Converters"
Then added window resources:
<Window.Resources>
<converters:FailuresTickConverter x:Key="failuresTickConverter" />
<converters:FailuresCrossConverter x:Key="failuresCrossConverter" />
</Window.Resources>
Then i have the classes themselves:
namespace Blah.Blah.Converters
{
public class FailuresTickConverter : IValueConverter
{
public object Convert( object value, Type targetType,
object parameter, CultureInfo culture )
{
int failures = (int)value;
if( failures > 0 )
return Visibility.Hidden;
return Visibility.Visible;
}
public object ConvertBack( object value, Type targetType,
object parameter, CultureInfo culture )
{
throw new NotImplementedException();
}
}
public class FailuresCrossConverter : IValueConverter
{
public object Convert( object value, Type targetType,
object parameter, CultureInfo culture )
{
int failures = ( int )value;
if( failures > 0 )
return Visibility.Visible;
return Visibility.Hidden;
}
public object ConvertBack( object value, Type targetType,
object parameter, CultureInfo culture )
{
throw new NotImplementedException();
}
}
}
Then in my XAML on the images i've done this:
<Image Visibility="{Binding Failures, Converter=failuresTickConverter}"
HorizontalAlignment="Center"
Width="10"
Height="10"
Grid.Column="2"
Grid.Row="0"
Source="/Content/Images/Tick.png">
</Image>
<Image Visibility="{Binding Failures, Converter=failuresCrossConverter}"
HorizontalAlignment="Center"
Width="10"
Height="10"
Grid.Column="2"
Grid.Row="0"
Source="/Content/Images/Cross.png">
</Image>
I'm getting an error on the bindings:
IValueConverter does not support converting from string
Elaborating on my comment, here's a simple (not the only one, of course) way to do it:
Create a converter to convert number to visibility:
public class PositiveToVisibilityConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return (int)value > 0 ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
Add the namespace of the converter to your xaml, add the converter to resources (use your own namespace of course):
<Window ...
xmlns:converters="clr-namespace:WpfApplication1.Converters"
...>
<Window.Resources>
<converters:PositiveToVisibilityConverter x:Key="PositiveConverter"/>
</Window.Resources>
Then put both the images in, the "success" one first and bind the property using the converter to the "failure" one:
<Image HorizontalAlignment="Center"
Width="10"
Height="10"
Grid.Column="2"
Source="/Content/Images/Tick.png"
Visibility="{Binding Failures, Converter={StaticResource PositiveConverter}}">
</Image>
<Image HorizontalAlignment="Center"
Width="10"
Height="10"
Grid.Column="2"
Source="/Content/Images/Cross.png">
</Image>
Since these images are in a grid (I assume) and have the same position and size, they will overlap and normally the one that's defined last will be drawn last, so the first one will not be visible. That is, unless the binding makes the second image invisible.
I'm using a ComboBox (WPF 4.0) to show user defined paragraph styles for an editor app. The ComboBox has two columns:
(1) Name of the paragraph style
(2) Text "abcABC123", should in some properties be formatted according to the paragraph style in the first column
(1) is working, (2) is not because _ResourceKey_background, _ResourceKey_foreground and _ResourceKey_fontFamily are no ResourceKeys
but variables containing ResourceKeys. How can I solve this?
_NameInternal, _NameUI, _ResourceKey_background, _ResourceKey_foreground and _ResourceKey_fontFamily are public properties
of the user defined paragraph style class.
<ComboBox Name="_cbStylesPara" SelectedValuePath="_NameInternal"
ItemsSource="{Binding Source={StaticResource _collectionViewSource_stylesPara}}" >
<ComboBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Grid.Column="0" Text="{Binding _NameUI}" VerticalAlignment="Center" />
<TextBlock Grid.Column="1" Text="abcABC123" Margin="3,0,0,0" VerticalAlignment="Center"
Background="{DynamicResource _ResourceKey_background}"
Foreground="{DynamicResource _ResourceKey_foreground}"
FontFamily="{DynamicResource _ResourceKey_fontFamily}" />
</Grid>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
As like you said resources are declared under App resources, what you can do is create an IValueConverter and return the resource value from it's Convert method.
public class ResouceLookupConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
return App.Current.TryFindResource(value);
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
return Binding.DoNothing;
}
}
XAML:
<ComboBox>
<ComboBox.Resources>
<local:ResouceLookupConverter x:Key="ResouceLookupConverter"/>
</ComboBox.Resources>
......
<TextBlock Grid.Column="1" Text="abcABC123" Margin="3,0,0,0"
VerticalAlignment="Center"
Background="{Binding _ResourceKey_background,
Converter={StaticResource ResouceLookupConverter}}"
Foreground="{Binding _ResourceKey_foreground,
Converter={StaticResource ResouceLookupConverter}}"
FontFamily="{Binding _ResourceKey_fontFamily,
Converter={StaticResource ResouceLookupConverter}}" />
</ComboBox>
Note: Ofcourse you have to define local namespace in your XAML set to the namespace where your Converter is declared.
I have a datagrid with grouping and I am trying to style the template to add in some summary about the group.
IN XAML DataGrid.RowGroupHeaderStyle
<Grid Grid.Column="3" Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Stretch" Margin="0,1,0,1" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding Name}" Margin="4,0,0,0" />
<TextBlock Grid.Column="1" Text="{Binding Items, Converter="{StaticResource summaryConverter}"}" />
</Grid>
Binding of data grid items source
PagedCollectionView collection = new PagedCollectionView(e.Result.ToList<MyClass>());
collection.GroupDescriptions.Add(new PropertyGroupDescription("Name"));
dataGrid.ItemsSource = collection;
MyClass
class MyClass {
public string Name;
public double Value;
}
I have created a converter to grab the Items of the same group but I am facing problem in converting the object into List<MyClass>(). I receive this error
Unable to cast object of type 'System.Collections.ObjectModel.ReadOnlyObservableCollection1[System.Object]' to type 'System.Collections.Generic.List1[MyClass]'.
`
In Converter.cs
public object Convert(object values, Type targetType, object param, CultureInfo culture) {
var source = (List<MyClass>)values;
}
Does anyone know how should I do the conversion??
Use LINQ.
public object Convert(object values, Type targetType, object param, CultureInfo culture) {
var source = (ReadOnlyObservableCollection<object>) values;
List<MyClass> list = source.OfType<MyClass>().ToList();
...
}