WPF: multiple controls binding to same property

最后都变了- 提交于 2019-12-24 09:59:48

问题


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?


回答1:


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




回答2:


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}}"/>


来源:https://stackoverflow.com/questions/5377072/wpf-multiple-controls-binding-to-same-property

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!