TextBox.Foreground.Opacity属性的奇怪行为

时间:2012-01-13 07:50:38

标签: silverlight user-interface silverlight-4.0

我创建了一个silverlight模板控件。 Thouse控件包含4个元素:2个文本框和2个文本块。 标记(在generic.xaml中):

<Style TargetType="local:InputForm">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="local:InputForm">
                    <Border Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}">
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition />
                                <RowDefinition />
                            </Grid.RowDefinitions>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition/>
                                <ColumnDefinition/>
                            </Grid.ColumnDefinitions>
                            <TextBlock Text="Login" Grid.Column="0" Grid.Row="0"/>
                            <TextBlock Text="Password" Grid.Column="0" Grid.Row="1"/>
                            <TextBox x:Name="LoginTextBox" Grid.Column="1" Grid.Row="0" Text="Login..."/>
                            <TextBox x:Name="PasswordTextBox" Grid.Column="1" Grid.Row="1" Text="Password..."/>
                        </Grid>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

在代码文件中,我从模板中获取文本框,并设置Foreground.Opacity属性等于0.5。 代码:

public class InputForm : Control
{
    private TextBox _loginTextBox;
    private TextBox _passwordTextBox;

    public InputForm()
    {
        this.DefaultStyleKey = typeof(InputForm);
    }

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();

        _loginTextBox = this.GetTemplateChild("LoginTextBox") as TextBox;
        _passwordTextBox = this.GetTemplateChild("PasswordTextBox") as TextBox;

        SetInActive();
    }

    private void SetInActive()
    {
        _loginTextBox.Foreground.Opacity = .5;
        _passwordTextBox.Foreground.Opacity = .5;
    }
}

当我在silverlight应用程序中添加此控件时,所有textboxs元素开始用Foreground.Opacity = 0.5表示文本 开始申请:

First tab before oper login tab

选择&#34;登录&#34;标签:

Login tab

回到&#34;一些信息&#34;标签:

First tab after open login tab

示例位于此处:http://perpetuumsoft.com/Support/silverlight/SilverlightApplicationOpacity.zip 是银光虫还是我做错了什么?

1 个答案:

答案 0 :(得分:1)

问题是Foreground属性的类型为Brush,它是一个引用类型(类)。

分配.Opacity = 0.5时,您正在更改引用的Brush的不透明度值。引用相同画笔的所有其他元素都将受到影响。

通常我们会在控件模板中使用VisualStateManager中的Storyboard来指定不同“状态”中控件的视觉外观。

然而,您的代码的快速修复将是:

private void SetInActive()     
{     
    Brush brush = new SolidColorBrush(Colors.Black) { Opacity = 0.5 };
    _loginTextBox.Foreground = brush    
    _passwordTextBox.Foreground= brush
}