Passing current combobox item to Converter using converterparamter - c#

I have one Enum Description Converter
public class EnumDescriptionConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
//// parameter need current item, but null or "Value"
if (Enum.IsDefined(value.GetType(), value) == false)
return System.Windows.DependencyProperty.UnsetValue;
string parameterString = Enum.GetName(value.GetType(), value);
if (parameterString == null)
return System.Windows.DependencyProperty.UnsetValue;
var desc = (value.GetType().GetField(parameterString).GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault() as DescriptionAttribute);
if (desc != null)
return desc.Description;
else
return parameter.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
i like to Pass current combobox item to converter as ConverterParameter
<ComboBox Name="test" Grid.Column="1" Grid.Row="2" VerticalAlignment="Center" IsReadOnly="True" >
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource enumDescriptionConverter},ConverterParameter=Value}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
but Value is coming as string "Value", when i try binding getting error. Is any way to pass current item ?

You don't need a converter parameter for this. Simply replace:
value.GetType().GetField(parameterString)
with
value.GetType().GetField(value.ToString())
You can get rid of parameterString entirely. The string representation of a singular enum value always matches the field name for that value (or, in cases where multiple enum elements have the same value, it will match the field name for an equivalent value).

Related

RadioButton bound to the Enum shows error on the unselected radiobutton

I have two radio buttons with Right and Left options:
<RadioButton Content="Right" Margin="5" VerticalAlignment="Center" IsChecked="{Binding Path=Direction, Mode=TwoWay, Converter={StaticResource EnumConverter}, ConverterParameter=Right}"/>
<RadioButton Content="Left" Margin="5" VerticalAlignment="Center" IsChecked="{Binding Path=Direction, Mode=TwoWay, Converter={StaticResource EnumConverter}, ConverterParameter=Left}"/>
The following Enum to Boolean converter code
public class EnumBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string parameterString = parameter as string;
if (parameterString == null)
return DependencyProperty.UnsetValue;
if (Enum.IsDefined(value.GetType(), value) == false)
return DependencyProperty.UnsetValue;
object parameterValue = Enum.Parse(value.GetType(), parameterString);
return parameterValue.Equals(value);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string parameterString = parameter as string;
if (parameterString == null)
return DependencyProperty.UnsetValue;
return Enum.Parse(targetType, parameterString);
}
}
Now when I select the radio button Right, the Left option shows error( a red border arround the radiobutton control with Left); and vise versa
how to fix this?
Found the solution, adding it just in case anyone needs.
Problem is, it is trying to pick the validation style from the application.
So I have to decorate the each element of the Radio button it with
Validation.ErrorTemplate="{x:Null}"
Thanks!

binding images in listbox

I have a listbox that is populated from a datatable. I want each item to have a specific image on listbox, but I want to set the image depending of an id that each item has.
for example , I have :
Products
Orange
Apple
ID
1
2
and the images are named: Item.1.png , Item.2.png
So, in my listbox,where I have apple, I will have next to it the image named: Item.2.png.
My problem is that I don't know how could I do a conditional binding . I don't want to have on my template hundreds of lines that are doing this for each item. I need to do this using a condition, like : if(product.id==1), Image.Source=Item.1.png.
Is there any way to do this in wpf?
It sounds to me like you need an IdToImageConverter that will decides which Image should be shown dependant on the value of the Id property. Something like this should do the trick:
[ValueConversion(typeof(int), typeof(ImageSource))]
public class IdToImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value.GetType() != typeof(int) || targetType != typeof(ImageSource)) return false;
int id = (int)value;
if (id < 0) return DependencyProperty.UnsetValue;
string imageName = string.Empty;
switch (id)
{
case 1: imageName = "Item.1.png"; break;
case 2: imageName = "Item.2.png"; break;
}
if (imageName.IsEmpty()) return null;
return string.Format("/AppName;component/ImageFolderName/{0}", imageName);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
You could then use it in your ListBox.ItemTemplate something like this:
<YourConvertersXmlNamespacePrefix:IdToImageConverter x:Key="IdToImageConverter" />
...
<ListBox ItemsSource="{Binding Items}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Id, Converter={StaticResource
IdToImageConverter}}" />
<TextBlock Text="{Binding Name}" Margin="5,0,0,0" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
As I understand your question, every object in the listbox has an ID property, where you want the image to be item.ID.png.
You could use a converter in your binding to do this. So in your listbox template, you can have something like:
// ... Listbox template
<Image Source={Binding pathToItemID, Converter={StaticResource MyConverter}/>
// ... Remaining ListBox template
You will need to add the converter to the UserControl's resources:
<UserControl.Resources>
<xmlnsPointingToConverter:MyConverter x:Key="MyConverter"/>
</UserControl.Resources>
Then add a MyConverter class which implements IValueConverter:
public class MyConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return string.Format("item.{0}.png", value);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}

How can we handle Null Values while Binding data to Text block in Windows phone

Hear i Have a confusion while Binding the data to Text Block in Windows phone
I have Text Block
<TextBlock Name="strytxt"
Text="{Binding STORY}"
Height="auto"
Width="Auto"
TextWrapping="Wrap"/>
in STORY Object some time I have Empty/Null Values
At that Time im Getting Some space in my UI
Now i Want to Make Visibility of the Textbox in to Collapsed if i get Null in that row
How can i do this
To change the Visibility of the TextBlock when the Binding value is null you need to use a Converter that converts from null/not null to Visible/Collapsed.
HereĀ“s a converter that converts the values. The converter handles an empty string as null, so that it return Collapsed for string.empty.:
public class NullToVisibilityConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
bool isVisible = value == null ? false : true;
if (isVisible) {
string stringValue = value as string;
if (stringValue != null) {
isVisible = string.IsNullOrEmpty(stringValue) ? false : true;
}
}
if (System.ComponentModel.DesignerProperties.IsInDesignTool) {
return Visibility.Visible;
}
return isVisible ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
throw new NotImplementedException();
}
}
You can apply the converter to the TextBlock as follows:
<UserControl.Resources>
<local:NullToVisibilityConverter x:Key="NullToVisibilityConverter"/>
</userControl.Resources>
<TextBlock Name="strytxt"
Visibility="{Binding STORY, Converter={StaticResource nullToVisibilityConverter}}"/>
Another alternativ is to display a Text when the value is null, you can specify that in the binding
<TextBlock Name="strytxt"
Text="{Binding STORY, TargetNullValue='is Null'}"/>
You can use a value converter to convert the value to a visibility:
public class NullToVisibiltyConverter : IValueConverter {
public Object Convert(Object value, Type targetType, Object parameter, CultureInfo culture) {
return value == null ? Visibility.Collapsed : Visibility.Visible;
}
public Object ConvertBack(Object value, Type targetType, Object parameter, CultureInfo culture) {
throw new NotImplementedException();
}
}
You then bind the Visibility of the TextBlock using the converter:
<TextBlock Name="strytxt"
Text="{Binding STORY}"
Height="auto"
Width="Auto"
TextWrapping="Wrap"
Visibility="{Binding STORY, Converter={StaticResource NullToVisibilityConverter}}"/>
You need to add an instance of the converter to a resource dictionary to be able to reference it in the binding:
<UserControl.Resources>
<local:NullToVisibilityConverter x:Key="NullToVisibilityConverter"/>
</userControl.Resources>

Windows Phone 8 bind to string resource with format

My localized resource string, named TextResource has the value: Text: {0}. Where {0} is the placeholder for String.Format.
My user control has a DependecyProperty called Count.
I would like to bind Count to the text of a text box but also apply the localized string. So that the content of the text block is Text: 5 (assuming the value of Count is 5)
I managed to figure out how to bind the localized string
<TextBlock Text="{Binding Path=LocalizedResources.TextResource, Source={StaticResource LocalizedStrings}}" />
or the property value
<TextBlock Text="{Binding Path=Count}" />
but not both simultaneous.
How can I do that in XAML?
PS: One option would be to add two text blocks instead of one but I am not sure if that is a good practice.
You have three options here.
First option: Modify your view model to expose your formatted string and bind to that.
public string CountFormatted {
get {
return String.Format(AppResources.TextResource, Count);
}
}
<TextBlock Text="{Binding Path=CountFormatted}" />
Second option: Make a converter MyCountConverter
public class MyCountConverter: IValueConverter {
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
if (value == null)
return value;
return String.Format(culture, AppResources.TextResource, value);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
throw new NotImplementedException();
}
}
<phone:PhoneApplicationPage.Resources>
<local:MyCountConverter x:Key="MyCountConverter"/>
</phone:PhoneApplicationPage.Resources>
...
<TextBlock Text="{Binding Count, Converter={StaticResource MyCountConverter}}"/>
Third option: Use bind-able converter parameter so that you can make a general StringFormat converter where you can actually bind the converter parameter. This is not supported out of the box in windows phone but is still doable. Check this link on how it can be done.
However, unless you are using resources to support multiple languages then it's much easier to just pass your format as a plain string to a converter.
<TextBlock Text="{Binding Count,
Converter={StaticResource StringFormatConverter},
ConverterParameter='Text: {0}'}" />
You'll have to make a StringFormatConverter converter that uses the parameter in this case.
Edit:
Regarding third option, you can use the IMultiValueConverter in the link above to achieve what you want. You can add the following converter:
public class StringFormatConverter: IMultiValueConverter {
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
var param = values[0].ToString();
var format = values[1].ToString();
return String.Format(culture, format, param);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) {
throw new NotImplementedException();
}
}
<TextBlock Text="{Binding ElementName=MultiBinder, Path=Output}" />
<binding:MultiBinding x:Name="MultiBinder" Converter="{StaticResource StringFormatConverter}"
NumberOfInputs="2"
Input1="{Binding Path=Count, Mode=TwoWay}"
Input2="{Binding Path=LocalizedResources.TextResource, Source={StaticResource LocalizedStrings}}" />
I don't know if it's worth the effort though.

WPF RadioButton InverseBooleanConverter not working

I have two RadioButtons which I am binding to a boolean property in the ViewModel. Unfortunately I am getting an error in the converter because the 'targetType' parameter is null.
Now I wasn't expecting the targetType parameter coming through to be null (I was expecting True or False). However I noticed that the IsChecked property of the RadioButton is a nullable bool so this kind of explains it.
Can I correct something in the XAML or should I be changing the solution's existing converter?
Here's my XAML:
<RadioButton Name="UseTemplateRadioButton" Content="Use Template"
GroupName="Template"
IsChecked="{Binding UseTemplate, Mode=TwoWay}" />
<RadioButton Name="CreatNewRadioButton" Content="Create New"
GroupName="Template"
IsChecked="{Binding Path=UseTemplate, Mode=TwoWay, Converter={StaticResource InverseBooleanConverter}}"/>
This is the existing converter I am using solution wide InverseBooleanConverter:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if ((targetType != typeof(bool)) && (targetType != typeof(object)))
{
throw new InvalidOperationException("The target must be a boolean");
}
return !(((value != null) && ((IConvertible)value).ToBoolean(provider)));
}
You need to change the converter, or what's probably even better, use a new converter.
[ValueConversion(typeof(bool?), typeof(bool))]
public class Converter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (targetType != typeof(bool?))
{
throw new InvalidOperationException("The target must be a nullable boolean");
}
bool? b = (bool?)value;
return b.HasValue && b.Value;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value;
}
#endregion
}

Categories