Change image in xaml based on a value from another xaml - c#

I have a Views/Doc.xaml with:
<navigation:Page ....
<data:DataGrid>
<data:DataGridTemplateColumn Header="Actions" HeaderStyle="{StaticResource TextHeaderStyle}" >
<data:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid x:Name="gridDocumentColumns">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<HyperlinkButton x:Name="hlEmail" Grid.Column="1" Tag="{Binding Index}" Click="hlEmail_Click" >
<ToolTipService.ToolTip>
<ToolTip Tag="ToolTipEmail" Opened="toolTip_ActionOpened" />
</ToolTipService.ToolTip>
<Image Source="../images/close.png" Stretch="None" />
</HyperlinkButton>
</Grid>
</DataTemplate>
</data:DataGridTemplateColumn.CellTemplate>
</data:DataGridTemplateColumn>
</data:DataGrid>
..............
I have a second class Views/Controls/ReadDocs.xaml (). If a certain condition in ReadDocs.xaml Code Behind is true i want to change the image source in Views/Doc.xaml to ../images/open.png
How can i achieve this?

You can define a converter and pass a flag value to it.
This converter will returns a specific path depending upon the value you have passed.
Kindly refer the below converter for reference...
public sealed class ImagetoPathConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value == null)
{
return value = "ms-appx:///Assets/Images/bk/1.png";
}
else if (value.ToString() == "1")
{
return value = "ms-appx:///Assets/Images/bk/2.png";
}
else if (value.ToString() == "2")
{
return value = "ms-appx:///Assets/Images/bk/3.png";
}
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
Bind the converter in Source and pass your conditional value.

Related

Change Background color to an element of a CollectionView

A CollectionView creates DateTime objects through a method. I would like the element with today's Datetime to have a different Grid background when opening the page.
<CollectionView
x:Name="ColCalendar">
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid BackgroundColor="Gray" RowSpacing="0.1">
<Grid.RowDefinitions>
<RowDefinition Height="8"/>
</Grid.RowDefinitions>
<Label Grid.Row="0" Text="{Binding Giorno}" FontSize="8" TextColor="White" HorizontalTextAlignment="Center"/>
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
The only method I know of to be able to change the background is the GestureRecognizer but it requires the user to press the button, instead I would like it to be automatic
use an IValueConverter
in your page (see docs for complete example)
<ContentPage.Resources>
<ResourceDictionary>
<local:DateColorConverter x:Key="DateColor" />
</ResourceDictionary>
</ContentPage.Resources>
...
<Grid BackgroundColor="{Binding DateField,Converter={StaticResource DateColor}}" RowSpacing="0.1">
then create a ValueConveter class
public class DateColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if ( ((DateTime)value).Today == DateTime.Today) return Color.Blue;
return Color.Yellow;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}

How to choose grid Columns from some Tabs and display them in another Tab?

I'm creating a WPF application(UI) with a TabControl which contains four TabItems in it.
My Application --
From the User Tab, I want to choose somehow (maybe with a check box, or any other way) which of the GridColumns will be displayed at the User Tab. I can work with the other Tabs, but sometimes I need to give the user the opportunity to work only with the specific outputs he/she wants. How can I make this work? I am new to C# and wpf, so if you could explain a simple solution and offer some codes, I would appriciate it.
Before answering your question, a brief hint for you: when you ask, post some code, otherwise it will be hard that someone spends time for helping you.
For implementing your application you need to consider:
ElementName data binding
ElementName data binding can't work in the ColumnDefinitions property
To solve the point number 2 you can read this very interesting article by Josh Smith.
Pratically he creates a special kind of ElementSpy with an attached property:
public class ElementSpy : Freezable
{
private DependencyObject element;
public static ElementSpy GetNameScopeSource(DependencyObject obj)
{
return (ElementSpy)obj.GetValue(NameScopeSourceProperty);
}
public static void SetNameScopeSource(DependencyObject obj, ElementSpy value)
{
obj.SetValue(NameScopeSourceProperty, value);
}
public static readonly DependencyProperty NameScopeSourceProperty =
DependencyProperty.RegisterAttached("NameScopeSource", typeof(ElementSpy), typeof(ElementSpy),
new UIPropertyMetadata(null, OnNameScopeSourceProperty));
private static void OnNameScopeSourceProperty(DependencyObject d, DependencyPropertyChangedEventArgs args)
{
INameScope nameScope;
ElementSpy elementSpy = args.NewValue as ElementSpy;
if (elementSpy != null && elementSpy.Element != null)
{
nameScope = NameScope.GetNameScope(elementSpy.Element);
if (nameScope != null)
{
d.Dispatcher.BeginInvoke(new Action<DependencyObject, INameScope>(SetScope),
System.Windows.Threading.DispatcherPriority.Normal,
d, nameScope);
}
}
}
private static void SetScope(DependencyObject d, INameScope nameScope)
{
NameScope.SetNameScope(d, nameScope);
}
public DependencyObject Element
{
get
{
if (element == null)
{
PropertyInfo propertyInfo = typeof(Freezable).GetProperty("InheritanceContext",
BindingFlags.NonPublic | BindingFlags.Instance);
element = propertyInfo.GetValue(this, null) as DependencyObject;
if (element != null)
{
Freeze();
}
}
return element;
}
}
protected override Freezable CreateInstanceCore()
{
return new ElementSpy();
}
}
Now we can use binding in our XAML
<Window.Resources>
<local:BooleanWidthConverter x:Key="BooleanWidthConverter" />
<local:ElementSpy x:Key="ElementSpy" />
</Window.Resources>
<StackPanel HorizontalAlignment="Stretch">
<Grid local:ElementSpy.NameScopeSource="{StaticResource ElementSpy}"
Margin="0,0,0,30">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="{Binding ElementName=cb1, Path=IsChecked, Converter={StaticResource BooleanWidthConverter}, Mode=OneWay}" />
<ColumnDefinition Width="{Binding ElementName=cb2, Path=IsChecked, Converter={StaticResource BooleanWidthConverter}, Mode=OneWay}" />
<ColumnDefinition Width="{Binding ElementName=cb3, Path=IsChecked, Converter={StaticResource BooleanWidthConverter}, Mode=OneWay}" />
</Grid.ColumnDefinitions>
<TextBlock HorizontalAlignment="Center" Text="Column 1" Margin="4" Grid.Column="0" />
<TextBlock HorizontalAlignment="Center" Text="Column 2" Margin="4" Grid.Column="1" />
<TextBlock HorizontalAlignment="Center" Text="Column 3" Margin="4" Grid.Column="2" />
</Grid>
<CheckBox x:Name="cb1" Content="Column 1" Margin="4" IsChecked="true" HorizontalAlignment="Center" />
<CheckBox x:Name="cb2" Content="Column 2" Margin="4" IsChecked="true" HorizontalAlignment="Center" />
<CheckBox x:Name="cb3" Content="Column 3" Margin="4" IsChecked="true" HorizontalAlignment="Center" />
</StackPanel>
To complete our code, we need a simple converter:
public class BooleanWidthConverter : IValueConverter
{
private static GridLength star = new GridLength(1, GridUnitType.Star);
private static GridLength zero = new GridLength(0, GridUnitType.Pixel);
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool boolValue = (bool)value;
return boolValue ? star : zero;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
Of course this is just a sample prototype, but I am sure it can help you with your application.

Show XAML on Condition

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.

How to convert back from string to Enum

I have a a class which is made of property information of a target(like type and values ). Iam using this UI to show all types on view in graphical format like Enum with comboboxes and boolean with checkboxes.Everything works well for me except the case when I change combobox value in UI,it does not change in viewmodel.Every time I change value in combobox it calls convertback method in my converter.I need to convert this string to enum type,I can write the convertback code easily for a particular enum type ,but how can I convert all other enums with this converter,I have the information of Type in PropertyType property that I can pass to converter and use it but I have no idea how to do it.
This is my UI code (only relevant part)
<!-- Default DataTemplate -->
<DataTemplate x:Key="DefaultDataTemplate">
<Grid Margin="4" MinHeight="25">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="Key" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Name}" FontWeight="Bold" />
<TextBox Margin="8,0" Grid.Column="1" Text="{Binding Value}" />
</Grid>
</DataTemplate>
<!-- DataTemplate for Booleans -->
<DataTemplate x:Key="BooleanDataTemplate">
<Grid Margin="4" MinHeight="25">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="Key" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Name}" FontWeight="Bold" />
<CheckBox Margin="8,0" Grid.Column="1" IsChecked="{Binding Value}" />
</Grid>
</DataTemplate>
<!-- DataTemplate for Enums -->
<DataTemplate x:Key="EnumDataTemplate">
<Grid Margin="4" MinHeight="25">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="Key" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Name}" FontWeight="Bold" />
<ComboBox Margin="8,0" SelectedItem="{Binding Value,Converter={StaticResource EnumToStringConverter},Mode=TwoWay}"
ItemsSource="{Binding PropertyType,
Converter={local:EnumToListConverter}}" Grid.Column="1"
HorizontalAlignment="Stretch" />
</Grid>
</DataTemplate>
<!-- DataTemplate Selector -->
<local:PropertyDataTemplateSelector x:Key="templateSelector"
DefaultnDataTemplate="{StaticResource DefaultDataTemplate}"
BooleanDataTemplate="{StaticResource BooleanDataTemplate}"
EnumDataTemplate="{StaticResource EnumDataTemplate}"/>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<ListView Grid.Row="0" ItemsSource="{Binding Model,Converter={StaticResource PropConverter}, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged, NotifyOnSourceUpdated=True}" Grid.IsSharedSizeScope="True"
HorizontalContentAlignment="Stretch"
ItemTemplateSelector="{StaticResource templateSelector}"
/>
and my converter and view model
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string EnumString;
try
{
EnumString = Enum.GetName((value.GetType()), value);
return EnumString;
}
catch
{
return string.Empty;
}
}
public object ConvertBack(object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
return null;
//What to do here
}
View model
public class PropertyValue
{
private PropertyInfo propertyInfo;
private object baseObject;
public PropertyValue(PropertyInfo propertyInfo, object baseObject)
{
this.propertyInfo = propertyInfo;
this.baseObject = baseObject;
}
public string Name
{
get { return propertyInfo.Name; }
}
public Type PropertyType { get { return propertyInfo.PropertyType; } }
public object Value
{
get { return propertyInfo.GetValue(baseObject, null); }
set
{
propertyInfo.SetValue(baseObject, value , null);
}
}
}
Try
return (targetType)Enum.Parse(typeof(targetType), value.ToString());
In ConvertBack, is targetType the correct enum type?
If so, I think this should work:
Enum.Parse(targetType, (String)value)
you shoud do it like this
enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 };
string colorName = "Blue";
if (Enum.IsDefined(typeof(Colors), colorName)) //true
{
Colors clr = (Colors)Enum.Parse(typeof(Colors), colorName);
}
colorName = "Orange";
if (Enum.IsDefined(typeof(Colors), colorName)) //false
{
Colors clr = (Colors)Enum.Parse(typeof(Colors), colorName);
}
I dont think its feasible to do this with converter or with multibinding.I solved my problem by not using the converter for combobox and checking value in getter and setter.
I modified my class which holds the property info and it works now,I am putting a special check for enum type ,rest of the types I can use converters.
public class PropertyValue
{
private PropertyInfo propertyInfo;
private object baseObject;
public PropertyValue(PropertyInfo propertyInfo, object baseObject)
{
this.propertyInfo = propertyInfo;
this.baseObject = baseObject;
}
public string Name
{
get { return propertyInfo.Name; }
}
public Type PropertyType
{
get { return propertyInfo.PropertyType; }
}
public object Value
{
get
{
var retVal = propertyInfo.GetValue(baseObject, null);
if (PropertyType.IsEnum)
{
retVal = retVal.ToString();
}
return retVal;
}
set
{
if (PropertyType.IsEnum)
{
value = Enum.Parse(propertyInfo.PropertyType, value.ToString());
}
propertyInfo.SetValue(baseObject, value, null);
}
}
}
I dont like corrupting view model for that but I cant see any option at this moment.Please let me know if there are any risks in my code or if you have a better approach.
What I could think quickly is that you can create one class EnumDescriptor with just two properties: EnumString (string) and EnumType (Type)
Your "EnumToListConverter" can return list of EnumDescriptor and you can bind display value of combobox to EnumString property.
In your "EnumToStringConverter", in Convert() you can create instance of EnumDescriptor as we have type and name of enum there, in ConvertBack() you will get the instance of EnumDescriptor from where you can parse the enum value and return it.
Thanks

Conversion from ReadOnlyObservableCollection to List<MyClass>

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();
...
}

Categories

Resources