textbox visibility/collapsed in silverlight mvvm - silverlight

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... !

Related

CheckBox Binding with Viewmodel property and IConverter not working

I have a simple CheckBox and I want to bind a value from my ViewModel to the IsChecked property of the CheckBox. The value derived from ViewModel is of type sbyte.
I have included a small converter class for that.
However, this code is not working.
Please suggest the right way of doing this.
XAML
<UserControl>
<UserControl.Resources>
<local:TrueFalseConverter x:Key="TFC"/>
</UserControl.Resources>
<CheckBox x:Name="chkOutOfSales" DataContext="{Binding DCIM}" IsChecked="{Binding CurrentRec.Out_of_Sales, Converter={StaticResource TFC},Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</UserControl>
Code Begind converter:
public class TrueFalseConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return ((bool)value == true) ? 1 : 0;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return ((sbyte)value == 1) ? true : false;
}
}
I found the solution...I had mistyped Out_Of_Sales as Out_of_Sales in my viewmodel...that was the issue...:-).
Thanks for your time..

try to convert textbox value to int within convert method

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

Why is binding to "Self" not working?

I try to bind the control's Tag property to the control's Visibility property, but I receive the following error in VS:
object reference not set to an instance of an object
The XAML is like below:
<RadioButton GroupName="NavButtonSide"
Tag="7"
Visibility="{Binding Path=Tag,
Converter={StaticResource ControlTagVisibilityConverter},
RelativeSource={RelativeSource Mode=Self}}"/>
Can anyone tell me how to solve it?
Nothing wrong with your binding. This works fine for me;
<Window.Resources>
<local:ControlTagVisibilityConverter x:Key="ControlTagVisibilityConverter" />
</Window.Resources>
<RadioButton
Tag="7"
Visibility="{Binding Path=Tag,
Converter={StaticResource ControlTagVisibilityConverter},
RelativeSource={RelativeSource Mode=Self}}"/>
ControlTagVisibilityConverter.cs
public class ControlTagVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var valueAsString = (string) value;
var valueAsInt = int.Parse(valueAsString);
switch (valueAsInt)
{
case 7:
return Visibility.Visible;
default:
return Visibility.Hidden;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}

Silverlight 4: how to switch control visibility

I am using MVVM in my Silverlight app. When control visibility is need to be managed by data, I am connecting its 'Visibility' property to object's corresponding property:
XAML:
<TextBlock Text="Price" Visibility="{Binding PriceVisibility, Mode=OneWay}"/>
<TextBox Text="{Binding TicketPrice, Mode=TwoWay}" Visibility="{Binding PriceVisibility, Mode=OneWay}"/>
CodeBehind (C#):
public string PriceVisibility { get { return PriceVisible ? "Visible" : "Collapsed"; } }
But from my perspective, returning string representation of the Visibility property is not a best approach.
Could you please advise if there are any better way?
Thanks!
I just used Reflector to inspect the type converters in the PresentationFramework.dll
There is already an implementation that can convert between boolean and visibility. You should be able to make use of this in your silverlight application.
public sealed class BooleanToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
bool flag = false;
if (value is bool)
{
flag = (bool) value;
}
else if (value is bool?)
{
bool? nullable = (bool?) value;
flag = nullable.HasValue ? nullable.Value : false;
}
return (flag ? Visibility.Visible : Visibility.Collapsed);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return ((value is Visibility) && (((Visibility) value) == Visibility.Visible));
}
}
I've faced the problem of binding a Boolean value to the visibility property, so I've implemented my own Boolean to Visibility Converter, I'm using it with most of my applications.
Add the Following Class to your application:
public class BoolVisibilityConverter : IValueConverter{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture){
bool isVisible = (bool)value;
return isVisible ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture){
System.Windows.Visibility currVisibility = (System.Windows.Visibility)value;
return (currVisibility == System.Windows.Visibility.Visible);
}
}
Now To Use it you'll need to add it as a resource in your XAML Code.
<UserControl.Resources>
<Helpers:BoolVisibilityConverter x:Key="boolVisibilityConverter" />
</UserControl.Resources>
In your example use the following:
<TextBlock Text="Price" Visibility="{Binding PriceVisibility, Mode=OneWay, Converter={StaticResource boolVisibilityConverter}}"/>
<TextBox Text="{Binding TicketPrice, Mode=TwoWay}" Visibility="{Binding PriceVisibility, Mode=OneWay, Converter={StaticResource boolVisibilityConverter}}"/>

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