how to bind HorizontalOptions property of label in xamarin.forms - c#

How to bind the HorizontalOptions attribute of Label in Xamarin.Forms`
<Label TextColor="#01B6FF" Text="{Binding RecepientFullName}" FontSize="Small" HorizontalOptions="{Binding TextAlign} />`

<ContentPage.Resources>
<ResourceDictionary >
<local:ChatTextAlignmentConverter x:Key="ChatTextAlignmentConverter">
</local:ChatTextAlignmentConverter>
</ResourceDictionary>
</ContentPage.Resources>
<Frame Margin="10,0,10,0" Padding="10,5,10,5" HorizontalOptions="{Binding TextAlign, Converter={StaticResource ChatTextAlignmentConverter}}" BackgroundColor="{Binding BackgroundColor}"/>
public class ChatTextAlignmentConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null)
{
string valueAsString = value.ToString();
switch (valueAsString)
{
case ("EndAndExpand"):
{
return LayoutOptions.EndAndExpand;
}
case ("StartAndExpand"):
{
return LayoutOptions.StartAndExpand;
}
default:
{
return LayoutOptions.StartAndExpand;
}
}
}
else
{
return LayoutOptions.StartAndExpand;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}

Related

Not controlled exception in WPF XAML: The specified conversion is not valid

I have a MVVM WPF application. I have below converter:
public class PrintIconVisibilityValueConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values[0] == null || values[1] == null) return Visibility.Collapsed;
int item1 = (int)values[0];
string item2 = (string)values[1];
if (item1 > 0 || !string.IsNullOrEmpty(item2))
{
return Visibility.Visible;
}
else
{
return Visibility.Collapsed;
}
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
From my view I do:
<Window.Resources>
<classes:PrintIconVisibilityValueConverter x:Key="PrintIconVisibilityValueConverter"/>
</Window.Resources>
then I have an image in this view:
<Image Source="/MyImages;component/Images/PrintIco.png"
Height="15" Margin="20 0 5 0">
<Image.Visibility>
<MultiBinding Converter="{StaticResource PrintIconVisibilityValueConverter}">
<Binding Path="Item1" />
<Binding Path="Item2" />
</MultiBinding>
</Image.Visibility>
</Image>
Item1 and Item2 are public properties in view model:
private string _item2 = string.Empty;
public string Item2
{
get
{
return _item2;
}
set
{
if (_item2 == value) return;
_item2 = value;
OnPropertyChanged("Item2");
}
}
private int _item1;
public int Item1
{
get
{
return _item1;
}
set
{
if (_item1 == value) return;
_item1 = value;
OnPropertyChanged("Item1");
}
}
It compiles correctly and I can execute the application without problems but in design time, the view is not show, an error says Not controlled exception and points to the line:
int item1 = (int)values[0];
within PrintIconVisibilityValueConverter class.
Below the screenshots of the exception shown on view:
Some suggestions;
Call the GetIsInDesignMode method in your converter and return immediately if it returns true:
public class PrintIconVisibilityValueConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))
return Visibility.Visible;
...
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Set the DataContext in XAML:
<Window.DataContext>
<local:ViewModel />
</Window.DataContext>
Set the design time data context:
<Window ... d:DataContext ="{d:DesignInstance {x:Type local:ViewModel}, IsDesignTimeCreatable=True}">
Or Disable XAML UI designer

Bind a buttons visibility in XAML to a viewmodel?

I want the button to be visible in State.Away and State.Stop but for some reason the button is always visible even if the State is different than State.Away and State.Stop.
Xaml:
<Button Text="Hello" IsVisible="{Binding View}"/>
ViewModel:
private bool myBool;
public bool View
{
get
{
if (State == State.Away || State == State.Gone)
{
myBool = true;
}
else
{
myBool = false;
}
return myBool;
}
}
You can create an IValueConverter from State to Visibility
public class StateToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
if (value is State)
{
State state = (State)value;
switch (state)
{
case State.Away:
case State.Gone:
return Visibility.Visible;
default:
return Visibility.Collapsed;
}
}
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
return State.None; // your default state
}
}
Then you bind your button to the converter
<Window.Resources>
<local:StateToVisibilityConverter x:Key="StateToVisibilityConverter"/>
</Window.Resources>
<Button Text="Hello" Visibility="{Binding Path=State, Converter={StaticResource StateToVisibilityConverter}}"/>

How to set ToolTip Visibility for the Grid column using DependencyProperty inside of IValueConverter

I want to set Visibility for ToolTip (DependencyProperty) inside of IValueConverter using special logic. I want to show/hide ToolTip only when I have the special condition.
How can I do this?
</UserControl.Resources>
<converters:ToolTipMessageConverter x:Key="ToolTipMessageConverter" />
</UserControl.Resources>
<telerik:RadGridView ItemsSource="{Binding Data}" AutoGenerateColumns="False">
<telerik:GridViewDataColumn DataMemberBinding="{Binding DataField}">
<telerik:GridViewDataColumn.ToolTipTemplate>
<TextBlock Text="{Binding OtherData,Converter={StaticResource ToolTipMessageConverter}}" Visibility=??? />
</telerik:GridViewDataColumn.ToolTipTemplate>
</telerik:GridViewDataColum>
<telerik:RadGridView>
public class ToolTipMessageConverter : FrameworkElement, IValueConverter
{
public Visibility ToolTipVisibility
{
get { return (Visibility)GetValue(ToolTipVisibilityProperty); }
set { SetValue(ToolTipVisibilityProperty, value); }
}
public static readonly DependencyProperty ToolTipVisibilityProperty =
DependencyProperty.Register("ToolTipVisibility", typeof(Visibility), typeof(ToolTipMessageConverter), new PropertyMetadata(Visibility.Visible));
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var status = (string)value;
var mess = string.Empty;
if (status == "Available")
{
this.SetValue(ToolTipVisibilityProperty, Visibility.Hidden);
}
else
{
mess = "User message... " + value;
this.SetValue(ToolTipVisibilityProperty, Visibility.Visible);
}
return mess;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}
So it should work:
<TextBlock Text="{Binding OtherData,Converter={StaticResource ToolTipMessageConverter}}" Visibility="{Binding ToolTipVisibility, Source={StaticResource ToolTipMessageConverter}}" />

Xamarin Forms / XAML: Converter not called

Does anybody know why only the second isvisible converter gets called?
If I changed the sequence, then only the new second converter get called.
Converter1 is DiaryTypeNahrungsaufnahmeToBoolConverter and converter2 is DiaryTypeAuswirkungToBoolConverter.
<ListView>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<RelativeLayout IsVisible="{Binding Type, Converter={StaticResource converter1}}"></RelativeLayout>
<RelativeLayout IsVisible="{Binding Type, Converter={StaticResource converter2}}"></RelativeLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
The Converter code is:
public class DiaryTypeNahrungsaufnahmeToBoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
try
{
if (value is LibChemotherapie.DiaryType)
{
return ((LibChemotherapie.DiaryType)value) == LibChemotherapie.DiaryType.Food;
}
return false;
}
catch (Exception)
{
return false;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
public class DiaryTypeAuswirkungToBoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
try
{
if (value is LibChemotherapie.DiaryType)
{
return ((LibChemotherapie.DiaryType)value) == LibChemotherapie.DiaryType.Effect;
}
return false;
}
catch (Exception)
{
return false;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Thanks for Help.
By the hint from Jason, it's working now! I changed the xaml, so that the ViewCell only consists one view. In that view I added my two relative layouts with the binding property.
<ListView>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<RelativeLayout>
<RelativeLayout IsVisible="{Binding Type, Converter={StaticResource converter1}}"></RelativeLayout>
<RelativeLayout IsVisible="{Binding Type, Converter={StaticResource converter2}}"></RelativeLayout>
</RelativeLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

How to Implement a BoolToVisibilityConverter

In my app I would like to toggle the visibility of an item in a StackPanel. My Stackpanel contains an Image and a TextBlock. How would I properly use a BoolToVisibilityConverter to toggle the visibility of the TextBlock, and save this setting for the users benefit?
Currently what I have is as follows, although I am getting a few errors. Important note, I need to use an ApplicationBar menu item as the click event that drives the toggling of the TextBox visibility.
EDIT
Error no longer occurring although the visibility of the TextBlock is not changing.
XAML
xmlns:common="clr-namespace:TestApp.Common"
<phone:PhoneApplicationPage.Resources>
<common:BooleanToVisibilityConverter x:Key="BoolToVisConv" />
</phone:PhoneApplicationPage.Resources>
<ListBox Name="ListBoxEffects" SelectionMode="Single" ItemsSource="{Binding}" Margin="{Binding}"
toolkit:TiltEffect.IsTiltEnabled="True" SelectionChanged="ListBox_SelectionChanged"
ItemContainerStyle="{StaticResource ListBoxItemStyle1}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<toolkit:WrapPanel ItemWidth="159" ItemHeight="Auto" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical" >
<Image Source="{Binding Thumbnail}" Width="155" Height="155" />
<TextBlock Text="{Binding Name}" Visibility="{Binding IsTextBlockVisible, Converter={StaticResource BoolToVisConv}}" TextWrapping="Wrap" FontSize="{StaticResource PhoneFontSizeNormal}" VerticalAlignment="Center" HorizontalAlignment="Center" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Code Behind
private void BuildLocalizedApplicationBar()
{
ApplicationBar = new ApplicationBar();
ApplicationBarMenuItem showFilterNamesMenuItem = new ApplicationBarMenuItem();
if (Settings.ShowFilterNames.Value)
showFilterNamesMenuItem.Text = AppResources.EditPage_EffectNames_Hide;
else
showFilterNamesMenuItem.Text = AppResources.EditPage_EffectNames_Show;
showFilterNamesMenuItem.Click += showFilterNamesMenuItem_Click;
ApplicationBar.MenuItems.Add(showFilterNamesMenuItem);
}
void showFilterNamesMenuItem_Click(object sender, EventArgs e)
{
if(Settings.ShowFilterNames.Value)
{
((ApplicationBarMenuItem)ApplicationBar.MenuItems[0]).Text = AppResources.EditPage_EffectNames_Hide;
Settings.ShowFilterNames.Value = false;
//Toggle the text block visibility to here
}
else
{
((ApplicationBarMenuItem)ApplicationBar.MenuItems[0]).Text = AppResources.EditPage_EffectNames_Show;
Settings.ShowFilterNames.Value = true;
//Toggle the text block visibility to here
}
}
A class for the BooleanToVisibilityConverter
//Error on BooleanToVisibilityConverter stating does not implement interface member 'System.Windows.Data.IValueConverter.Convert(object, System.Type, object, System.Globalization.CultureInfo)
public class BooleanToVisibilityConverter : IValueConverter
{
public class BooleanToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo language)
{
return (value is bool && (bool)value) ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo language)
{
return value is Visibility && (Visibility)value == Visibility.Visible;
}
}
Try this:
public class BooleanToVisibilityConverter : IValueConverter
{
private object GetVisibility(object value)
{
if (!(value is bool))
return Visibility.Collapsed;
bool objValue = (bool)value;
if (objValue)
{
return Visibility.Visible;
}
return Visibility.Collapsed;
}
public object Convert(object value, Type targetType, object parameter, string language)
{
return GetVisibility(value);
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
Here is mine:
public class BoolToVisConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
return (value is bool && (bool)value) ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
return value is Visibility && (Visibility)value == Visibility.Visible;
}
}
There is already an implemenation of the converter: http://msdn.microsoft.com/en-us/library/system.windows.controls.booleantovisibilityconverter(v=vs.110).aspx

Categories