wpfbinding

WPF: multiple controls binding to same property


Hello
I'm trying to change several controls' property according to some environment variables and i want to avoid creating a property for each control in the datacontext, so i thought using a converter which sets the property according to control name. Goal is to use one property for all controls:

<Grid.Resources>
   <local:NameToStringConverter x:Key="conv" />    
</Grid.Resources>

<TextBlock Name="FordPerfect" 
     Text="{Binding ElementName="FordPerfect" Path=Name, Converter={StaticResource conv}, Mode=OneWay}"/>
<TextBlock Name="Arthur" 
     Text="{Binding ElementName="Arthur" Path=Name, Converter={StaticResource conv}, Mode=OneWay}"/>
<TextBlock Name="ZaphodBeeblebrox" 
     Text="{Binding ElementName="ZaphodBeeblebrox" Path=Name, Converter={StaticResource conv}, Mode=OneWay}"/>

and ...

public class NameToStringConverter : IValueConverter
{
    public object Convert(
     object value, Type targetType,
     object parameter, CultureInfo culture)
    {            
        if (MyGlobalEnv.IsFlavor1 && ((string)value).Equals("ZaphodBeeblebrox")) return "42"
        if (MyGlobalEnv.IsFlavor2 && ((string)value).Equals("ZaphodBeeblebrox")) return "43"
        if (MyGlobalEnv.IsFlavor1 && ((string)value).Equals("Arthur")) return "44"

        return "?";
    }

    public object ConvertBack(
     object value, Type targetType,
     object parameter, CultureInfo culture)
    {
        throw new NotSupportedException("Cannot convert back");
    }
}

I'm sure there's a better and more elegant way... Any ideas?


Solution

  • The point of oneway databinding is just to decouple UI (XAML) from code (CS). Here, your code and UI are tied so tightly together that trying to do this through databinding is really not buying you anything. You might simplify things by writing a method that takes the data value and applies it correctly to each control - still tightly coupled (bad) but at least the code is condensed and easy to follow (less bad).

    What you should probably do though is not rely on the control name but define a ConverterParameter.