Coder Social home page Coder Social logo

valueconverters.net's Introduction

ValueConverters.NET

Version Downloads

This library contains a collection of most commonly used implementations of the IValueConverter interface. ValueConverters are used to convert values bound from the view to the view model - and in some cases also backwards.

Download and Install ValueConverters

This library is available on NuGet: https://www.nuget.org/packages/ValueConverters/

Use the following command to install ValueConverters using NuGet package manager console:

PM> Install-Package ValueConverters

If your target platform is Xamarin.Forms use following NuGet package:

PM> Install-Package ValueConverters.Forms

If your target platform is .NET MAUI use following NuGet package:

PM> Install-Package ValueConverters.MAUI

API Usage

The usage of converters is on all platforms more or less the same:

  • Define the converter in the resources area of the view/page/usercontrol.
  • Use the converter in a binding by referenceing it as a StaticResource.

General Usage of Converters in XAML

Define a converter in the Resources section of a UserControl, Window, Page, etc. Specify options if required.

 <UserControl.Resources> 
        <ResourceDictionary> 
            <converters:DateTimeConverter x:Key="DateTimeConverter" Format="d" MinValueString="-"/> 
        </ResourceDictionary> 
    </UserControl.Resources> 

Apply the converter as a StaticResource:

<TextBox Text="{Binding EmployeeDetailViewModel.Birthdate, Converter={StaticResource DateTimeConverter}}"/> 

Using EnumWrapperConverter

EnumWrapperConverter is used to display localized enums. The concept is fairly simple: Enums are annotated with localized string resources and wrapped into EnumWrapper. The view uses the EnumWrapperConverter to extract the localized string resource from the resx file. Following step-by-step instructions show how to localize and bind a simple enum type in a WPF view:

  1. Define new public enum type and annotate enum values with [Display] attributes:
    [DataContract] 
    public enum PartyMode 
    { 
        [EnumMember] 
        [Display(Name = "PartyMode_Off", ResourceType = typeof(PartyModeResources))] 
        Off, 

        // … 
    } 
  1. Create StringResources.resx and define strings with appropriate keys (e.g. "PartyMode__Off"). Make sure PublicResXFileCodeGenerator is used to generate the .Designer.cs file. (If ResXFileCodeGenerator is used, the resource lookup operations may require more time to complete).

  2. Create StringResources.resx for other languages (e.g. StringResources.de.resx) and translate all strings accordingly. Use Multilingual App Toolkit for easy localization of the defined string resources.

  3. Expose enum property in the ViewModel.

        public PartyMode PartyMode 
        { 
            get { return this.partyMode; } 

            set { this.partyMode = value; 
                  this.OnPropertyChanged(() => this.PartyMode); } 
        } 
  1. Bind to enum property in the View and define Converter={StaticResource EnumWrapperConverter}.
        <Label Content="{Binding PartyMode, Converter={StaticResource EnumWrapperConverter}}" /> 

That’s it. If you want to change the UI language at runtime, don’t forget to call OnPropertyChanged after changing CurrentUICulture. There is a WPF sample app available.

Converter Culture

Value converters are culture-aware. Both the Convert and ConvertBack methods have a culture parameter that indicates the cultural information. If cultural information is irrelevant to the conversion, then you can ignore that parameter in your custom converter.

By default, the culture parameter is provided by the underlaying platform. If you want to override the provided culture, use the property PreferredCulture. You can select from one of the following override behaviors:

  • PreferredCulture.ConverterCulture: Default, uses the converter culture provided by the underlying platform.
  • ConverterCulture.CurrentCulture: Overrides the default converter culture with CultureInfo.CurrentCulture.
  • ConverterCulture.CurrentUICulture: Overrides the default converter culture with CultureInfo.CurrentUICulture.

This is particularly helpful in WPF applications, since it is a known/unresolved bug that the provided culture parameter does not update when CultureInfo.CurrentCulture or CultureInfo.CurrentUICulture is updated. Use ValueConvertersConfig.DefaultPreferredCulture to configure the default converter culture for all converters.

Links

License

ValueConverters.NET is Copyright © 2021 Thomas Galliker. Free for non-commercial use. For commercial use please contact the author.

valueconverters.net's People

Contributors

lostmsu avatar thomasgalliker avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

valueconverters.net's Issues

What is the final licence of the project?

Github depicts MIT, Nuget repo says Apache 2.0, which both allow free for commercial use with attribution and mention of the author.
On the other hand on the bottom of Readme/Home page on Github, it is written that for commercial use, contact the author?

Can you provide some clarification please?

License in Readme

The license text in the readme states regarding the license

CrossPlatformLibrary is Copyright © 2016 Thomas Galliker. Free for non-commercial use. For commercial use please contact the author.

This has the wrong project name (copy & paste?) and contradicts the license file that states that the code is licensed under MIT.

[Enhancement] Enum/Any Member description converter

For ToolTip.

public enum NicType
{
    [Description("xxx")]
    Ethernet,
    [Description("xxx")]
    Wlan,
    [Description("xxx")]
    Vm,
    [Description("xxx")]
    Ohter
}
<Label ToolTip="{Binding NicType, Converter={StaticResource EnumDescriptionConverter}}" />

Further, a generic MemberDescriptionConverter can be implemented, supporting not only Enum, but any member modified by the Description attribute.

String reference not set when creating CultureInfo.

I am using version 2.0.20011.1 of the nuget.

Symptoms
I have the following rendering error :

System.ArgumentNullException: String reference not set to an instance of a String.
Parameter name: name
   at System.Globalization.CultureInfo..ctor(String name, Boolean useUserOverride)
   at ValueConverters.ConverterBase.Windows.UI.Xaml.Data.IValueConverter.Convert(Object value, Type targetType, Object parameter, String culture)
   at PlexSync.Dialogs.SelectServerUserDialog.SelectServerUserDialog_obj1_Bindings.Update_ViewModel_IsServerVisible(Boolean obj, Int32 phase)

How I used it
Here is the resource definition in app.xaml :

<Application
   ...
   xmlns:converters="using:ValueConverters" />

   <Application.Resources>
      <ResourceDictionary>
         <converters:BoolToVisibilityConverter x:Key="BoolToVisibility" />
      </ResourceDictionary>
   </Application.Resources>
</Application>

Here is where I use it :

...
        <Grid Visibility="{x:Bind ViewModel.IsServerVisible, Converter={StaticResource BoolToVisibility}}">
...

Ideas for new converters

What do you think of adding the following converters:

  • StringIsNullOrEmptyConverter (or adding invertion on StringIsNotNullOrEmptyConverter)
  • AddConverter (wich calculates: value 1 parameter)
  • SubtractConverter (wich calculates: value - parameter)

Add/Subtract: I am not sure on what datatype it is best to do the calculation. Im my case int is good enough, but what others might need?

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    if (int.TryParse(value?.ToString(), out var basis)
        && int.TryParse(parameter?.ToString(), out var subtract))
        return basis - subtract;

    return value;
}

.Net Core 3 compatibility?

ValueConverters is currently only supported in .Net Framework and Xamarin.Forms projects. .Net Core 3.x also has an IValueConverter interface so we could extend the support for this library too.

Support .NET 5.0

Package 'ValueConverters 2.0.20011.1' was restored using '.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2, .NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1, .NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8' instead of the project target framework 'net5.0-windows7.0'. This package may not be fully compatible with your project.

Would love to see this project updated to support .NET 5.0.

Suggestion: support for NoesisGUI

Maybe add version with NoesisGUI support? It should be easy, just a #if #else in usings section of files. Of course, users could do this themselves, but such support out of the box would be nice.

[Bug]The Debug.WriteLine in DebugConverter was deleted in the Nuget Package

Source Code:

namespace ValueConverters
{
public class DebugConverter : SingletonConverterBase
{
protected override object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
Debug.WriteLine("DebugConverter.Convert(value={0}, targetType={1}, parameter={2}, culture={3}",
value ?? "null",
(object)targetType ?? "null",
parameter ?? "null",
(object)culture ?? "null");

        return value;
    }

    protected override object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        Debug.WriteLine("DebugConverter.ConvertBack(value={0}, targetType={1}, parameter={2}, culture={3}",
             value ?? "null",
             (object)targetType ?? "null",
             parameter ?? "null",
             (object)culture ?? "null");

        return value;
    }
}

}

The Decompiled code of DebugConverter in the Nuget Package:

namespace ValueConverters
{
public class DebugConverter : SingletonConverterBase
{
protected override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}

    protected override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value;
    }
}

}

[Enhancement] EnumToBoolConverter Support `Enum` ConverterParameter Type

Summary

Please provide a brief summary of your proposal. Two to three sentences is best here.

Support that ConverterParameter is Enum and not just String.
It can improve the flexibility for EnumToBoolConverter.

API Changes

Include a list of all API changes, additions, subtractions as would be required by your proposal.

EnumToBoolConverter

Intended Use Case

Provide a detailed example of where your proposal would be used and for what purpose.

<RadioButton Content="ON"
             IsChecked="{Binding EditType, Converter={x:Static conv:EnumToBoolConverter.Instance}, ConverterParameter={x:Static local:EditPanelValueType.Switch}, Mode=TwoWay, FallbackValue={markups:False}}" />

[Enhancement] XmlnsPrefix and XmlnsDefinition

Summary

Add XmlnsPrefix to package and then user can simplify the definition of converter.

API Changes

Example code:

// AssemblyInfo.cs
[assembly: XmlnsPrefix("https://github.com/thomasgalliker/ValueConverters.NET", "vc")]
[assembly: XmlnsDefinition("https://github.com/thomasgalliker/ValueConverters.NET", "ValueConverters")]

After XmlnsPrefix and XmlnsDefinition, user can use following

<UserControl xmlns:vc="https://github.com/thomasgalliker/ValueConverters.NET">
</UserControl>

instead of

<UserControl xmlns:vc="clr-namespace:ValueConverters;assembly=ValueConverters">
</UserControl>

Intended Use Case

Provide a detailed example of where your proposal would be used and for what purpose.

<UserControl xmlns:vc="https://github.com/thomasgalliker/ValueConverters.NET">
</UserControl>

Howto cascade converters?

Currently I'm using the Tag property, which is kind of a hack :|

<vc:IsEmptyConverter x:Key="IsNotEmptyConverter" IsInverted="True" />
<vc:BoolToVisibilityConverter x:Key="BooleanToVisibility" />

<ItemsControl ItemsSource="{Binding Attributes}" 
    Name="AttributesItemsControl"
    Tag="{Binding Attributes, Converter={StaticResource IsNotEmptyConverter}}"
    Visibility="{Binding Tag, ElementName=AttributesItemsControl, Converter={StaticResource BooleanToVisibility}}"/>

What do you think about a usage like this? It would require a DependencyProperty 'PreviousConverter' somewhere in a base class and calling it if not null.

<vc:BoolToVisibilityConverter IsInverted="True" x:Key="VisibleIfNotEmptyConverter">
    <vc:BoolToVisibilityConverter.PreviousConverter>
        <vc:IsEmptyConverter />
    </vc:BoolToVisibilityConverter.PreviousConverter>
</vc:BoolToVisibilityConverter>

<!-- or -->

<vc:IsEmptyConverter x:Key="BooleanToVisibilityInverted" />
<vc:BoolToVisibilityConverter x:Key="VisibleIfNotEmptyConverter" 
                                IsInverted="True"
                                PreviousConverter="{StaticResource BooleanToVisibilityInverted}"/>

<!-- usage -->
<ItemsControl ItemsSource="{Binding Attributes}" 
    Visibility="{Binding Attributes, Converter={StaticResource VisibleIfNotEmptyConverter}}"/>

Additional converters?

StringEqualsMultiValueConverter - verifies if all given values are string.Equal and returns configurable TrueValue or FalseValue.

ReferenceEqualsMultiValueConverter - verifies if all given values are object.ReferenceEqual and returns configurable TrueValue or FalseValue.

StringStartsWith-/EndsWithConverter - verifies if given value.ToString() starts/ends with given parameter and returns configurable TrueValue or FalseValue.

Feel free to let me know if these are converters that you consider helpful for others and want to have included in your lib or not.

New version ?

Are you going to publish a new version soon ? (last 3 versions were "pre" versions)

Sponsor through GitHub

Please configure this project to be able to receive sponsoring through GitHub (custom values).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.