开发者

WPF: multiple controls binding to same property

开发者 https://www.devze.com 2023-02-17 22:45 出处:网络
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 conver

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, Conv开发者_StackOverflow社区erter={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?


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. See the bottom 1/3 of this article http://www.switchonthecode.com/tutorials/wpf-tutorial-binding-converters


You may bind directly to environment variable in your situation :

<Window xmlns:system="clr-namespace:System;assembly=mscorlib" ...>
<TextBlock Text="{Binding Source={x:Static system:Environment.OSVersion}}"/>
0

精彩评论

暂无评论...
验证码 换一张
取 消