標籤:layout HTST copy bst 技術分享 tco val bsp 檔案
允許轉載,轉載時請務必以超連結形式標明文章 原始出處 、作者資訊和本聲明。否則將追究法律責任。http://chengxingliang.blog.51cto.com/3972944/886643
ResourceDictionary是一個鍵控對象字典,可在 XAML 和代碼中使用。在其中我們可以定義樣式、模板等以方便在其他頁面中隨時調用。
首先我們建立一個ResourceDictionary頁面如:
然後向資源字典檔案中寫入以下代碼,分別是樣式和模板:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <!--資料範本--> <DataTemplate x:Key="lbTmp"> <StackPanel Orientation="Vertical" > <StackPanel Orientation="Horizontal" Margin="5" Width="380"> <TextBlock Text="{Binding ArtName}" Style="{StaticResource tbStyle}" Margin="5 10 0 0"></TextBlock> <TextBox Text="{Binding ArtContent}" Name="tbName" Margin="5"></TextBox> <TextBox Text="{Binding ArtAuthor}" Margin="5"></TextBox> <TextBlock Text="{Binding ArtUpdateTime}" Margin="5 10 0 0"></TextBlock> </StackPanel> <StackPanel Orientation="Horizontal" Visibility="Collapsed"> <TextBox Text="{Binding ArtContent}" Width="280"></TextBox> </StackPanel> </StackPanel> </DataTemplate> <!--樣式--> <Style x:Key="tbStyle" TargetType="TextBlock"> <Setter Property="FontWeight" Value="Bold"></Setter> <Setter Property="Foreground" Value="Red"></Setter> </Style></ResourceDictionary>
此時我們將此資源字典拷貝一份,僅僅只是將文字樣式中的字型顏色從藍色變為紅色。然後我們在App.xaml中載入這兩個資源字典,首先載入藍色字型的資源字典A,然後我們再載入紅色字型的資源字典B,代碼如下:
<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="SLResDic.App" > <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="ResourceDic.xaml" /> <ResourceDictionary Source="ResourceDic2.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources></Application>
載入此資源字典中的資源方法有以下兩種:
第一種Xaml直接載入,如下:
<Grid x:Name="LayoutRoot" Background="White" DataContext="{StaticResource SourceList}"> <TextBlock Name="tblock" Style="{StaticResource tbStyle}" HorizontalAlignment="Left" Width="100" Text="今天第一"></TextBlock> <ListBox x:Name="lbRes" ItemsSource="{Binding ArticleList}" Margin="0 50 0 0 " ItemTemplate="{StaticResource lbTmp}" HorizontalAlignment="Left" VerticalAlignment="Top" Height="400" > </ListBox> </Grid>
第二種後台載入:
public MainPage() { InitializeComponent(); DataTemplate dtemp = Application.Current.Resources["lbTmp"] as DataTemplate; lbRes.ItemTemplate = dtemp; }
效果如下:
從上面的效果來看我們生效的風格樣式是紅色的第二個資源字典。那時因為<ResourceDictionary.MergedDictionaries>資源字典合并的原因,後面添加的資源字典會覆蓋之前的同名key字典資源。
如需源碼請點擊 SLResDic.zip 下載,謝謝~
本文出自 “程興亮-Silverlight” 部落格,請務必保留此出處http://chengxingliang.blog.51cto.com/3972944/886643
Silverlight實用竅門系列:68.Silverlight的資源字典ResourceDictionary