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

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

Related

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 bind HorizontalOptions property of label in xamarin.forms

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;
}
}

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}}" />

MVVM Bind enum to Combobox [duplicate]

This question already has answers here:
WPF Binding a ListBox to an enum, displaying the Description Attribute
(6 answers)
Closed 7 years ago.
I'm using caliburn micro framework in a WPF application.
I need to bind this enum to a combobox.
Consider following enum in a ViewModel:
public enum MovieType
{
[Description("Action Movie")]
Action,
[Description("Horror Movie")]
Horror
}
How can I bind this enum to a combobox?
Is it possible to show the enum description insted of enum values in
combobox?
Can I implement IvalueConverter for this purpose?
In the resources of your Window/UserControl/? you have to create an ObjectDataProvider like:
<ObjectDataProvider x:Key="MovieDataProvider" MethodName="GetValues" ObjectType="{x:Type namespace:MovieType}">
<ObjectDataProvider.MethodParameters>
<x:Type Type="namespace:MovieType"/>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
To use it as itemssource of your ComboBox you have to do the following:
ItemsSource="{Binding Source={StaticResource MovieDataProvider}}"
If you want to display a custom value you can modify the ItemTemplate of your ComboBox like:
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={converters:MovieDisplayConverter}}"/>
</DataTemplate>
</ComboBox>
The MovieDisplayConverter can look like the following if you want to return custom values:
internal class MovieDisplayConverter : MarkupExtension, IValueConverter
{
private static MovieDisplayConverter converter;
public MovieDisplayConverter()
{
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is MovieType)
{
switch ((MovieType)value)
{
case MovieType.Action:
return "Action Movie";
case MovieType.Horror:
return "Horror Movie";
default:
throw new ArgumentOutOfRangeException("value", value, null);
}
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return converter ?? (converter = new MovieDisplayConverter());
}
}
If you want the description-attribute of your enum-values in the ComboBox replace the convert-method of the above converter with the following:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is MovieType)
{
FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
if (fieldInfo != null)
{
object[] attributes = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), true);
if (attributes.Length > 0)
{
return ((DescriptionAttribute)attributes[0]).Description;
}
}
}
return value;
}

NullToVisibilityConverter make visible if not null

Want to hide and show property grid for SelectedItem in listview
<UserControl xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
<ListView>
<!--here is list view-->
</ListView>
<xctk:PropertyGrid SelectedObject="{Binding Active}" Visibility="{Binding Active, Converter=NullToVisibilityConverter}" >
</xctk:PropertyGrid>
</UserControl>
So I need converter and use it in visibility property converter. Any help?
public class NullVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value == null ? Visibility.Hidden : Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Then reference the NullVisibilityConverter in your XAML Resources.
<StackPanel.Resources>
<simpleXamlContent:NullVisibilityConverter x:Key="NullToVisibilityConverter"/>
</StackPanel.Resources>
To use the converter we can create one in the resources, and refer to it as a static resource in the binding statement.
<UserControl xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit">
<UserControl.Resources>
<yournamespace:NullVisibilityConverter x:Key="NullToVisibilityConverter"/>
</UserControl.Resources>
<ListView>
<!--here is list view-->
</ListView>
<xctk:PropertyGrid SelectedObject="{Binding Active}" Visibility="{Binding Active, Converter={StaticResource NullToVisibilityConverter}}" >
</xctk:PropertyGrid>
</UserControl>
and Converter class itself
public class NullVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value == null ? Visibility.Hidden : Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
There is little more useful version allows to set default invisibility value:
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string defaultInvisibility = parameter as string;
Visibility invisibility = (defaultInvisibility != null) ?
(Visibility)Enum.Parse(typeof(Visibility), defaultInvisibility)
: Visibility.Collapsed;
return value == null ? invisibility : Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
Where ever in resources add:
<converters:NullReferenceToVisibilityConverter x:Key="NullToVis" />
And use it like there:
<StackPanel Visibility="{Binding MyObject, Converter={StaticResource NullToVis}}">
<StackPanel Visibility="{Binding MyObject, Converter={StaticResource NullToVis}, ConverterParameter=Hidden}">

Categories