2009-08-31 60 views
2

更改靜態資源在runtine是聽起來不可能的事情。Silverlight:在運行時更改靜態資源的屬性

我有一個文本框顯示一個簡單的數字。然後,我已經定義了一個風格,這改變TextBox的模板成爲一輪文本框:

<Style x:Key="RoundNumberDisplay" TargetType="TextBox"> 
     <Setter Property="Width" Value="22"/> 
     <Setter Property="Height" Value="22"/> 

     <Setter Property="Template"> 
      <Setter.Value> 

        <ControlTemplate> 
         <Border x:Name="brd1" Width="20" Height="20" CornerRadius="15"> 
          <TextBlock x:Name="txt1" Foreground="#222" TextAlignment="center" Text="1" FontSize="14" FontWeight="ExtraBold" VerticalAlignment="center" /> 
          <Border.Background> 
           <RadialGradientBrush GradientOrigin=".3, .3"> 
            <GradientStop Color="{StaticResource ColorBackground1}" Offset=".15"/> 
            <GradientStop Color="{StaticResource ColorForeground1}" Offset="1"/> 
           </RadialGradientBrush> 
          </Border.Background> 
         </Border> 
        </ControlTemplate> 

      </Setter.Value> 
     </Setter> 

    </Style> 

正如你所看到的,所顯示的文字是「硬連線」 TextBlock中的「txt1中」。很顯然,我不能在運行時更改數字。

我現在的問題是:什麼是最好的方式來改變顯示的數字?爲每個數字創建樣式對我來說看起來有點無效。

由於提前, 弗蘭克

回答

2

TemplateBinding能夠從目標文本框中設置txt1-Text-Property的值。重要提示:必須設置ControlTemplate的目標類型!

<Style ... 

        <ControlTemplate **TargetType="TextBox"**> 
          ... 

          <TextBlock x:Name="txt1" Foreground="#222" TextAlignment="center" **Text="{TemplateBinding Text}"** FontSize="14" FontWeight="ExtraBold" VerticalAlignment="center" /> 
        </ControlTemplate> 
    </Style> 
0

樣式只是控制的樣子,所以在實踐中就需要這種風格的多次重複使用。一個純粹主義者可能會說,你不應該在樣式中包含像數字那樣的數據(這些數據必須在你的應用程序上下文中)。所以,當你使用的樣式,你可以改變顯示的數字:

<TextBox Style={StaticResource RoundNumberDisplay} x:Name="TextBoxOne" Text="1"/> 

即使是這樣,你可能會偏向於結合文本到您的視圖模型(或任何你使用的數據),並從那裏拉數量。任何一個都可以。

+0

,因爲我不使用目標文本框的文本屬性,但該控件模板的TextBlock的「txt1中」,顯示文本的文本屬性,文本框」文本屬性值將被覆蓋。我需要使用TemplateBinding將Text-Value從目標TextBox獲取到TextBlock(請參閱我的自我答案) – Aaginor 2009-09-01 11:55:42