2013-04-17 18 views
2

我有一個這樣的風格:加載樣式只對特定的OS版本

<Style TargetType="{x:Type Button}"> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="{x:Type Button}"> 
       ... 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

默認情況下,將適用於所有的按鈕在所有的操作系​​統,但我只想要應用,如果用戶使用的是Windows 8.

有什麼辦法來激活從代碼隱藏式的檢查Environment.OSVersion.Version財產後?或者有沒有更好的方法來做到這一點?

回答

1

找到您的引導程序代碼(顯示XAML之前執行的代碼)並創建一個簡單的開關,它將根據操作系統版本選擇正確的XAML文件。

Uri uri = new Uri("/OS7.xaml", UriKind.Relative); 
StreamResourceInfo info = Application.GetResourceStream(uri); 
XamlReader reader = new System.Windows.Markup.XamlReader(); 
var dic = (ResourceDictionary)reader.LoadAsync(info.Stream); 

//then locate ResourceDictionary throgh Application.Current.Resources 
yourDictionary.MergedDictionaries.Add(dic); 

您還可以創建簡單的觸發器,結合靜態OS版本屬性和開關按鈕的模板,但它太有限了,因爲你可以只交換模板。它可能會幫助你;

<Window.Resources> 
        <ControlTemplate x:Key="OS7" TargetType="Button"> 
         <Border x:Name="Border" CornerRadius="2" BorderThickness="1" Background="blue" BorderBrush="blue"> 
          <ContentPresenter Margin="2" HorizontalAlignment="Center" VerticalAlignment="Center"/> 
         </Border> 
        </ControlTemplate> 


     <!-- DEFALT --> 
     <Style TargetType="Button"> 
      <Setter Property="Template"> 
       <Setter.Value> 
        <ControlTemplate TargetType="Button"> 
         <Border x:Name="Border" CornerRadius="2" BorderThickness="1" Background="red" BorderBrush="blue"> 
          <ContentPresenter Margin="2" HorizontalAlignment="Center" VerticalAlignment="Center"/> 
         </Border> 
        </ControlTemplate> 
       </Setter.Value> 
      </Setter> 

      <Style.Triggers> 
       <!-- Just an example. Replace IsMouseOver with DataTrigger and STATIC binding against OS version--> 
       <Trigger Property="IsMouseOver" Value="True"> 
        <Setter Property="Template" Value="{StaticResource OS7}" /> 
       </Trigger> 
      </Style.Triggers> 
     </Style> 
    </Window.Resources> 
1

我覺得風格是基於主題,並不能根據操作系統版本。

+0

是的,你可以做到這一點在後面的代碼。 –

+0

試試這個。寫不同的風格和在當頁面加載後面的代碼,檢查操作系統版本,然後基於從頁面發現資源像Page.TryFindResource(「ResouceName」)。將其轉換爲風格並分配給您想要分配的控制器。 –