Results 1 to 5 of 5

Thread: [RESOLVED] databinding with conversion? wpf vb.net 2010

  1. #1

    Thread Starter
    Fanatic Member Megalith's Avatar
    Join Date
    Oct 2006
    Location
    Secret location in the UK
    Posts
    879

    Resolved [RESOLVED] databinding with conversion? wpf vb.net 2010

    does anyone know how to bind an object to another and have it's value converted prior to display? My app has a scrollbar which i have bound to an image's left property so the image is scrolled as i move the scrollbar. ok so far but now i have added some labels i wish to bind also to the scrollbar which has given me an issue. How do i databind and convert the value of the scrollbar to a percentage? or conversely can i set the scrollbar to be from 0 to 100 (&#37 and convert the value to move the image.

    Having looked into this i have found something called an IValueConvertor but am unsure of how to implement it? Also will my xaml databindings be effected by this?
    If debugging is the process of removing bugs, then programming must be the process of putting them in.

  2. #2
    PowerPoster Evil_Giraffe's Avatar
    Join Date
    Aug 2002
    Location
    Suffolk, UK
    Posts
    2,555

    Re: databinding with conversion? wpf vb.net 2010

    Yes, an IValueConverter is what you need. Create a class that does the conversion in the Convert method defined by the interface (you can implement ConvertBack as simply throwing a NotSupportedException if you like, since you won't be doing two way binding with it).

    Then, in your XAML, define an instance of your converter class in the Resources, and then your binding needs to reference the resource in the Converter attribute of the binding.

  3. #3
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: databinding with conversion? wpf vb.net 2010

    As an example, here are a couple of classes that implement IValueConverter:
    csharp Code:
    1. public class PmsShortDateFormatConverter : IValueConverter
    2. {
    3.     public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    4.     {        
    5.         // It's stupid that we need to put in code to stop the designer complaining, but yet here it is:
    6.         if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))
    7.         {
    8.             return string.Empty;
    9.         }
    10.  
    11.         if (value == null)
    12.         {
    13.             return string.Empty;
    14.         }
    15.  
    16.         if (value.GetType() != typeof(DateTime) && value.GetType() != typeof(DateTime?))
    17.         {
    18.             throw new ArgumentException(string.Format("{0} is not a (nullable) DateTime object", value));
    19.         }
    20.  
    21.         var typedValue = (DateTime?) value;
    22.  
    23.         return typedValue.PmsShortDateFormat();
    24.     }
    25.  
    26.     public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    27.     {
    28.         throw new NotImplementedException();
    29.     }
    30. }
    csharp Code:
    1. public class NullableBooleanToYesNoConverter : IValueConverter
    2. {
    3.     /// <summary>
    4.     /// Converts a value.
    5.     /// </summary>
    6.     /// <returns>
    7.     /// A converted value. If the method returns null, the valid null value is used.
    8.     /// </returns>
    9.     /// <param name="value">The value produced by the binding source.</param>
    10.     /// <param name="targetType">The type of the binding target property.</param>
    11.     /// <param name="parameter">The converter parameter to use.</param>
    12.     /// <param name="culture">The culture to use in the converter.</param>
    13.     public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    14.     {
    15.         // It's stupid that we need to put in code to stop the designer complaining, but yet here it is:
    16.         if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))
    17.         {
    18.             return string.Empty;
    19.         }
    20.  
    21.         if (value == null)
    22.         {
    23.             return string.Empty;
    24.         }
    25.  
    26.         if (value.GetType() != typeof(bool) && value.GetType() != typeof(bool?))
    27.         {
    28.             throw new ArgumentException(string.Format("{0} is not a (nullable) Boolean object", value));
    29.         }
    30.  
    31.         var typedValue = (bool?)value;
    32.  
    33.         return typedValue.Value ? "Yes" : "No";
    34.     }
    35.  
    36.     /// <summary>
    37.     /// Converts a value.
    38.     /// </summary>
    39.     /// <returns>
    40.     /// A converted value. If the method returns null, the valid null value is used.
    41.     /// </returns>
    42.     /// <param name="value">The value that is produced by the binding target.</param>
    43.     /// <param name="targetType">The type to convert to.</param>
    44.     /// <param name="parameter">The converter parameter to use.</param>
    45.     /// <param name="culture">The culture to use in the converter.</param>
    46.     public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    47.     {
    48.         // It's stupid that we need to put in code to stop the designer complaining, but yet here it is:
    49.         if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))
    50.         {
    51.             return null;
    52.         }
    53.  
    54.         if (value == null)
    55.         {
    56.             return null;
    57.         }
    58.  
    59.         if (value.GetType() != typeof(string))
    60.         {
    61.             throw new ArgumentException(string.Format("{0} is not a String object", value));
    62.         }
    63.  
    64.         var typedValue = (string)value;
    65.         bool? result;
    66.  
    67.         switch (typedValue)
    68.         {
    69.             case "":
    70.                 result = null;
    71.                 break;
    72.             case "Yes":
    73.                 result = true;
    74.                 break;
    75.             case "No":
    76.                 result = false;
    77.                 break;
    78.             default:
    79.                 throw new ArgumentException(string.Format("{0} is not a valid String value", value));
    80.         }
    81.  
    82.         return result;
    83.     }
    84. }
    Then in XAML, this is in the Resources section:
    xml Code:
    1. <converters:PmsShortDateFormatConverter x:Key="PmsShortDateFormatConverter" />
    2. <converters:NullableBooleanToYesNoConverter x:Key="NullableBooleanToYesNoConverter" />
    an then this is how they're bound:
    xml Code:
    1. <TextBlock Grid.Row="0"
    2.            Grid.Column="1"
    3.            Margin="20,0,0,0"
    4.            Text="{Binding Certificate15CEntity.ReceivedDate, Converter={StaticResource PmsShortDateFormatConverter}}" />
    xml Code:
    1. <ComboBox Name="approvedComboBox"
    2.           Grid.Row="3"
    3.           Grid.Column="1"
    4.           Margin="20,0,0,0"
    5.           Width="Auto"
    6.           Height="Auto"
    7.           HorizontalAlignment="Stretch"
    8.           VerticalAlignment="Top"
    9.           ItemsSource="{Binding ApprovedOptions}"
    10.           SelectedItem="{Binding Certificate15CEntity.Approved, Mode=TwoWay, Converter={StaticResource NullableBooleanToYesNoConverter}}">
    11.     <ComboBox.Background>
    12.         <MultiBinding Converter="{StaticResource ValueChangedBackgroundConverterWhite}">
    13.             <Binding Path="Certificate15CEntity.Approved" />
    14.             <Binding Path="Certificate15CEntity.Approved" Mode="OneTime"/>
    15.         </MultiBinding>
    16.     </ComboBox.Background>
    17. </ComboBox>
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  4. #4

    Thread Starter
    Fanatic Member Megalith's Avatar
    Join Date
    Oct 2006
    Location
    Secret location in the UK
    Posts
    879

    Re: databinding with conversion? wpf vb.net 2010

    thx guys will go with limiting the scrollbar and binding the image left position with the converter. seems tidier that way than converting a number of pixels shifted into a percentage. let you know if i have any issues. Seems like a lot of work for a simple conversion but i'm thinking it will get easier as the app expands and other conversions of data are needed.

    For a technology that has existed since 2008 wpf help is scarce and i appreciate this site and the help i have had during this new learning curve. When i made a design choice to go with wpf i presumed (undoubtedly like a lot of people) that it was windows forms with more control over positioning elements of the ui, this i find is not the case but i'm hooked on it now lol
    If debugging is the process of removing bugs, then programming must be the process of putting them in.

  5. #5

    Thread Starter
    Fanatic Member Megalith's Avatar
    Join Date
    Oct 2006
    Location
    Secret location in the UK
    Posts
    879

    Re: databinding with conversion? wpf vb.net 2010

    Works perfect thx again for the help thread resolved
    If debugging is the process of removing bugs, then programming must be the process of putting them in.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width