WPF:多个控件绑定到同一个属性 [英] WPF: multiple controls binding to same property

查看:1501
本文介绍了WPF:多个控件绑定到同一个属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好结果
我试图按照一些环境变量来改变几个控件的财产,我想避免创建在DataContext的每个控件的属性,所以我想用转换器,它根据控件名称设置属性。目标是用一个属性对所有控件:

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

和...

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?

推荐答案

单向数据绑定的要点就是从code(CS)脱钩UI(XAML)。在这里,你的code和UI绑得那么紧在一起,试图通过数据绑定做到这一点实在是不买你什么。你可能会写,是以数据值和正确应用它的每个控制的方法简化事情 - 还是紧耦合(坏),但至少code冷凝,易于遵循(不坏)。

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).

你应该做的虽然是不依赖于控制的名字,但定义ConverterParameter。请参阅本文的 HTTP底部1/3:// WWW。 switchonthe code.com /教程/ WPF的教程结合转换器

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

这篇关于WPF:多个控件绑定到同一个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆