簡體   English   中英

通過App.xaml以編程方式設置樣式

[英]Programmatically Setting Style From App.xaml

我用代碼創建了一個新的Calendar控件:

  Calendar calendar = new Calendar();

我想使用我的app.xaml中定義的樣式設置其CalendarDayButtonStyle

  calendar.CalendarDayButtonStyle = ...

但是我不知道該怎么做。 另外,我沒有訪問“ FindResource”的權限,這是我看到的其他人使用的功能。 (我在ICommand內部,因此我無法訪問此方法)還有其他方法嗎?

您可以使用Application.Current.FindResource

這很簡單...

在您的應用程序中實例化ResourceDictionary

應用程式

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/AssemplyOfResource;Component/Resource.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

在代碼中檢索樣式

代碼背后

  object resource = Application.Current.FindResource("KeyName");
  if (resource != null && resource.GetType() == typeof(Style))
      calendar.Style = (Style)resource;

您會看到的大多數人都只是使用Application.Current.FindResource(“ KeyName”)並將其強制轉換,除非圖形設計者決定與ResourceDictionaries混淆。 這將導致應用程序不崩潰。

如果您需要一些特定的Calandar示例,請訪問:

MSDN雜志自定義新的WPF日歷控件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM