WPF 中動態改變控制項範本

來源:互聯網
上載者:User

標籤:style   blog   http   color   使用   io   檔案   2014   

在某些項目中,可能需要動態改變控制項的模板,例如軟體中可以選擇不同的主題,在不同的主題下軟體介面、控制項的樣式都會有所不同,這時即可通過改變控制項範本的方式實現期望的功能。基本方法是當使用者點擊切換主題按鈕是載入新的資源字典,並使用新載入的資源字典替代當前的資源字典這時要用到ResourceManager。假設現有兩個不同的資源字典檔案Dictionary1.xaml和Dictionary2.xaml存在於Themes檔案夾內:在MainPage中使用其中一個資源字典作為預設樣式檔案:
  <Window.Resources>        <ResourceDictionary>            <ResourceDictionary.MergedDictionaries>                <ResourceDictionary Source="Themes\Dictionary1.xaml"></ResourceDictionary>            </ResourceDictionary.MergedDictionaries>        </ResourceDictionary>    </Window.Resources>
後台即可通過如下代碼切換資源字典:
    private void Button_Click_1(object sender, RoutedEventArgs e)        {            ResourceDictionary newDictionary = new ResourceDictionary();            newDictionary.Source = new Uri("Themes/Dictionary1.xaml", UriKind.RelativeOrAbsolute);            this.Resources.MergedDictionaries[0] = newDictionary;        }        private void Button_Click_2(object sender, RoutedEventArgs e)        {            ResourceDictionary newDictionary = new ResourceDictionary();            newDictionary.Source = new Uri("Themes/Dictionary2.xaml", UriKind.RelativeOrAbsolute);            this.Resources.MergedDictionaries[0] = newDictionary;        }

如果不想讓控制項應用預設樣式,可以手動設定控制項的樣式為null:<Button Content="主題1" Style="{x:Null}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75"/>另一種方法:直接修改所用控制項的樣式、模板,但這時要保證控制項的樣式或模板引用為DynamicResource而非StaticResource。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.