How to use the codebehind variable as input for the ConverterParameter parameter in ValueConverter

I have a ListBox where I set an ItemSource to a CollectionViewSource that is populated from a WCF service. I am using a value converter in ListBox.ItemTemplate \ DataTemplate to convert properties into objects in ItemsSource.

Everything works as expected, but now I need to update the conversion process so that the converted value is still based on the property values ​​of individual objects, except when another property is equal to a specific value. And this value is set in the code behind xaml, this is the field level variable set in the page constructor.

To do this, I want to pass the field level variable as a ValueConverter ConverterParameter. I tried several ways, mainly using the ideas from this question , except that I always get an error when parsing xaml (and the application does not load).

One fix can add a property to objects in an ItemsSource, but I really don't want to. Partly because this object is used in several projects, so I do not want to change i .... and because I want to see if another method is possible. I also think wpf has MultiValue Converter (and possibly SL 4.0), but I'm on SL 3.0.

I guess that the problems that I have had so far are related to the timing of loading, binding and parsing xaml.

So a few questions:

  • , ?
  • , ?
  • ?
+3
1

, ConverterParameter . , , UserControl, , .

, , - .

 public class ExampleConverter : IValueConverter
 {

    public int SpecialValue { get; set; }

    public override object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value != null)
        {
             if (value.Equals(SpecialValue))
                 return "Special!";
             else
                 return value.ToString();
        }
        else
        {
             return null;
        }
    }

    public override object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

UserControl: -

<UserControl.Resources>
   <local:ExampleConverter x:Key="conv" SpecialValue="-1" />
</UserControl.Resources>

UserControl, : -

((ExampleConverter)Resources["conv"]).SpecialValue = someOtherVariable;
+5

Source: https://habr.com/ru/post/1779269/


All Articles