3

I sometimes have labels where the content changes dynamically with the values of some objects. The strings are static though, but they need to be changed accordingly to my attributes.

An easy way would be, to implement a converter which takes my object and returns my desired string. This would result in many converters which only have one task and can't be used in different cases.

I could also change my title in my ViewModel -> Is this the better approach?

Frame91
  • 3,670
  • 8
  • 45
  • 89
  • 1
    Create generic converter which will return string based on object type passed to it. Also you can use `DataTrigger` if converter is an issue for you. – Rohit Vats Mar 17 '14 at 08:12
  • Converters are a kind of glue for connecting Views to ViewModels. If there's no easy way to make a generic one, I personally don't see a big problem with having many small single purpose converters - each converter has a very clear and modular purpose, making your solution more readable. – Baldrick Mar 17 '14 at 08:18
  • 2
    I would handle these changes in the ViewModel. I personally don't like having many converters. The code is scattered and I find it somewhat hard to maintain. – Gerrit Fölster Mar 17 '14 at 09:12
  • Rohit, you should really post your response as an answer. That pretty much sums up the way the to deal with an unmaintainable number of converters. – ouflak Mar 17 '14 at 10:51

2 Answers2

2

In your view model you can have the dynamic label property as such

String DynamicLabel 
{
    get
    {
         if ( this.x == 1 )
         {
              return staticString1;
         }
         //etc etc 
    }
}

When ever the label needs changing you would just have to call

OnPropertyChanged("DynamicLabel")

and your xaml would look something along these lines

<textblock text="{Binding Path = DynamicLabel , updateSourceTrigger = OnPropertyChanged}"/>
Chris
  • 915
  • 8
  • 28
  • Thanks, I'll go with this approach ;) – Frame91 Mar 18 '14 at 06:49
  • Awesome, both answers are fine in general, I mainly stick to using the view model for properties and use converts to change the type e.g. bool to visibility and I guess that is what you are going for as well. – Chris Mar 18 '14 at 14:53
1

I think this may helpful to you, you can pass the parameters for different cases and check the conditions according to the parameter you passed in the converter.

Binding TestValue, Converter={StaticResource TestConverter}, ConverterParameter='Test'}

    public object Convert(object value, Type targetType, object parameter, string language)
    {
        if (parameter != null && parameter.Equals("Test"))
        { //Do some operation 
        }
    }

By using parameter you can do different operations in a single converter.

Sankarann
  • 2,625
  • 4
  • 22
  • 59
Ravi Shankar B
  • 472
  • 2
  • 4
  • 15