2012-01-13 52 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