try to convert textbox value to int within convert method - wpf

i trying binding textbox value to button IsEnable property but i get an exception.
this is my convert class:
public class BooleanToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string num = value as string;
int n = int.Parse(num);
if (n > 10) return true;
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
this is my xaml code:
<Button Content="Button" Grid.Column="1" IsEnabled="{Binding ElementName=mytext,Path=Text,Converter={StaticResource convertIntToBool}}" HorizontalAlignment="Left" Margin="83,181,-156,-179" Grid.Row="1" VerticalAlignment="Top" Width="74"/>
<TextBox Grid.Column="1" x:Name="mytext" HorizontalAlignment="Left" Height="23" Margin="263,163,-382,-163" Grid.Row="1" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>
i get FormatException: Input string was not in a correct format.

Ok so you want to handle user input in TextBox and make a button enabled or disabled according to this input.
First, you're using int.Parse, meaning that you trust the user to write a number in your TextBox: Don't ever trust user input.
You'll need to use int.TryParse so it doesn't throw an exception if the input isn't a number.
Second, I don't know why you set the TextBox's Text property to "TextBox", that's what is throwing the exception.
Your converter code should look like this:
public class BooleanToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string num = value as string;
int n;
if(int.TryParse(num, out n)) { //return true is the parse worked
if(n > 10) return true;
}
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}

Related

xaml Binding to enum. Display value instead of "ToString"

I have a property of an enum type. I bind the content of a wpf control to this property. This will display the name of the enum value. So the ToString Method of enum is called.
But I need to display the value, not the string value. Does anyone know how to do this?
This is my C# code:
public enum Animal
{
cat = 0,
dog = 1,
mouse = 2
}
public Animal MyAnimal { get; set; }
void SomeMethod() { MyAnimal = dog; }
This is in my XAML:
<Label Content="{Binding MyAnimal}">
When you bind to a value of one type and want to display it in another format than the default ToString() method provides you should either use a DataTemplate or an IValueConverter. Since XAML is a markup language you cannot really cast the enumeration value to an int in your markup so you should use a converter:
public class EnumConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
animals enumValue = (animals)value;
return System.Convert.ToInt32(enumValue);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
<Window.Resources>
<local:EnumConverter x:Key="conv" />
</Window.Resources>
...
<ContentControl Content="{Binding TheEnumProperty, Converter={StaticResource conv}}" />
I have found a solution:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!(value is Enum)) return value;
return Enum.IsDefined(value.GetType(), value) ? value : System.Convert.ToInt32(value);
}

WPF - binding complex objects to simple controls

I have created a class named "BoundProperty" which contains a property "Value".
Binding to a property which is an instance of that class looks this way
(Age is a BoundProperty):
<TextBox Text="{Binding MyModel.Age.Value, Mode=TwoWay}" />
Is there a way to make the binding look this way and additionally still retain it two-way?
<TextBox Text="{Binding MyModel.Age, Mode=TwoWay}" />
I can't use implicit/explicit conversion operators, for this "BoundProperty" initialization requires special parameters, which need to be copied from original object.
Thanks,
AD
If Value is public you can use ValueConverter:
public class BoundPropertyConverter:IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var age = value as BoundProperty;
if (age == null)
return string.Empty;
return age.Value;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
int age;
if (int.TryParse(value.ToString(), out age))
return new BoundProperty() {Value = age};
return null;
}
}
Then in xaml define namespace to this converter
xmlns:converters="clr-namespace:Your.Namespace"
And then in Resources area write something like this:
<converters:BoundPropertyConverter x:Key="BoundPropertyConverter"/>
And last but not least:
<TextBox Text="{Binding MyModel.Age, Mode=TwoWay, Converter={StaticResource BoundPropertyConverter}" />

textbox visibility/collapsed in silverlight mvvm

I Silverlight5 with mvvm pattern i have one doubt.
In xaml i have used one textblock and i bind some id in it.
If the textblock content value is 1 or 2 means
yet another textbox is visible or else that is collapsed.. how to acheive that..
my code:
<TextBlock Name="textBlock1" Text="{Binding id}" Loaded="textBlock1_Loaded" Visibility="Collapsed" />
<TextBox Text="{Binding name,Mode=TwoWay}" x:Name="t1" Visibility="{Binding IsVisible,Converter={StaticResource visibilityconverter}}" />
in view model i had created the property for id and raised the event and bind the value to textblock.
to convert the value to visible i have a visibilityconverter class in one separate folder named "Converters"
public class visibilityconverter:IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
if (id==1 && id==2)
{
return Visibility.Visible;
}
return Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
in the above visibleconverter class how i cna get the id value from viewmodel and check it..
If i got the value from viewmodel to visibilityconverter means i will proceed further.
tell me if u can..!
Hi i have found the solution..
In xaml give the following:
<TextBox Text="{Binding name,Mode=TwoWay}" x:Name="t1" Visibility="{Binding id,Converter={StaticResource visibilityconverter}}" />
In visibilityConverter class:
public class visibilityconverter:IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
string v = value.ToString();
if (v =="1" || v=="2")
{
return Visibility.Visible;
}
return Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Problem Solved... !

binding to a radio button

I have the following radio button bound to the variable IsAllowed
<RadioButton Name="YesRadioButton" Margin="5,5,0,0" IsChecked="{Binding Path=IsAllowed, Mode=TwoWay}">Yes</RadioButton>
How can I make the No button to take the opposite value only using XAML ?
You do not need to. It will happen by default.
Just make sure that IsAllowed starts off as true, and the rest will take care of its self.
This is because when you click on the No button, it will automatically set the Yes button's checked value (that's how radio buttons work), so the change will happen automatically and you backing class will be updated.
EVEN BETTER: Just use a check box. Yes/no situations are what they are designed for.
There is no Xaml-only solution. You could bind No using a reverse bool Converter though.
<local:NotConverter x:Key="notConverter"/>
{Binding IsAllowed, Mode=TwoWay, Converter=notConverter}
public class NotConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
Boolean result = false;
if (value is Boolean)
result = !((Boolean)value);
return result;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
Boolean result = false;
if (value is Boolean)
result = !((Boolean)value);
return result;
}
}
You will have to write converter using IValueConverter. Here is an example how to do it WPF - Bind to Opposite Boolean Value Using a Converter
The above answer works but I wanted a converter that would apply to both Yes and No radio buttons and reflect the value of nullable booleans. So I made the alternative that takes advantage of converter parameters:
public class YesNoRadioButtonToBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return CompareValueWithRequiredValueToBeChecked(value, parameter);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return CompareValueWithRequiredValueToBeChecked(value, parameter);
}
private bool CompareValueWithRequiredValueToBeChecked(object value, object parameterValue)
{
bool? convertedValue = ConvertObjectToBool(value);
bool? convertedParameter = ConvertObjectToBool(parameterValue);
bool result = convertedValue == convertedParameter;
return result;
}
private bool? ConvertObjectToBool(object parameter)
{
string stringResult = parameter == null ? null : parameter.ToString();
bool? convertedResult;
bool convertResultTest = false;
if (stringResult != null && !bool.TryParse(stringResult, out convertResultTest))
{
throw new InvalidCastException(string.Format("Cannot convert {0} to a bool.", parameter));
}
convertedResult = stringResult == null ? (bool?)null : (bool?)convertResultTest;
return convertedResult;
}
}
Here is what the XAML looks like:
<converters:YesNoRadioButtonToBooleanConverter x:Key="yesNoToBool" />
<RadioButton Content="Yes" Name="radYes" GroupName="Group1" IsChecked="{Binding Path=boolProperty1, Mode=TwoWay, Converter={StaticResource yesNoToBool}, ConverterParameter=true}" />
<RadioButton Content="No" Name="radNo" GroupName="Group1" IsChecked="{Binding Path=boolProperty1, Mode=TwoWay, Converter={StaticResource yesNoToBool}, ConverterParameter=false}" />

Set value to null in WPF binding

please take a look at the following line
<TextBox Text="{Binding Price}"/>
This Price property from above is a Decimal? (Nullable decimal).
I want that if user deletes the content of the textbox (i.e. enters empty string, it should automatcally update source with null (Nothing in VB).
Any ideas on how I can do it 'Xamly'?
I am using .NET 3.5 SP1 so it's very simple:
<TextBox Text="{Binding Price, TargetNullValue=''}"/>
Which stands for (thanks Gregor for your comment):
<TextBox Text="{Binding Price, TargetNullValue={x:Static sys:String.Empty}}"/>
sys is the imported xml namespace for System in mscorlib:
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Hope that helped.
This value converter should do the trick :
public class StringToNullableDecimalConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
CultureInfo culture)
{
decimal? d = (decimal?)value;
if (d.HasValue)
return d.Value.ToString(culture);
else
return String.Empty;
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
string s = (string)value;
if (String.IsNullOrEmpty(s))
return null;
else
return (decimal?)decimal.Parse(s, culture);
}
}
Declare an instance of this converter in the ressources :
<Window.Resources>
<local:StringToNullableDecimalConverter x:Key="nullDecimalConv"/>
</Window.Resources>
And use it in your binding :
<TextBox Text="{Binding Price, Converter={StaticResource nullDecimalConv}}"/>
Note that TargetNullValue is not appropriate here : it is used to define which value should be used when the source of the binding is null. Here Price is not the source, it's a property of the source...
You can try using a ValueConverter (IValueConverter)
http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx
Of the back of my head here, something like:
public class DoubleConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
return (double)value;
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
var doubleValue = Convert.ToDouble(value);
return (doubleValue == 0 ? null : doubleValue);
}
}
(Might need some tweaking though)

Resources