2012-01-13 50 views
2

我创建了一个silverlight模板控件。 Thouse控件由4个元素组成:2个文本框和2个文本块。 标记(在generic.xaml):与TextBox.Foreground.Opacity属性的奇怪行为

<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财产equels 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

选择 “登录” 选项卡:

Login tab

回到 “有些infromation” 选项卡:

First tab after open login tab

样品位于:http://perpetuumsoft.com/Support/silverlight/SilverlightApplicationOpacity.zip 它是Silverlight的bug还是我做错了什么?

回答

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 
} 
+0

非常感谢,它帮助我 – Sergey 2012-01-13 10:19:37