簡體   English   中英

迭代resourcedictionary xaml文件

[英]iterating resourcedictionary xaml file

我試圖根據xaml resourcedictionary文件中的顏色數量顯示一定數量的colorpicker控件。

由於某種原因,我無法找出正確的方法來執行此操作。 通過XAMLReader將其加載到ResourcesDictionary對象時,我不確定對其進行迭代的最佳方法是什么。

我首先嘗試使用XDocument.Elements()將其作為xml進行處理,當嘗試獲取所有元素時,它給出了一個空的IEnumerable。

做這個的最好方式是什么 ?

xaml的示例:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <!-- Edit the FontFamily  value to change the application font-->
    <FontFamily x:Key="NormalFontFamily">Arial</FontFamily>

    <!-- Edit ARGB values (hex) to change the colours used in the application -->
    <Color x:Key="NormalForegroundColor" A="0xFF" R="0xFF" G="0xFF" B="0xFF" />
    <Color x:Key="NormalForegroundColor80" A="0xFF" R="0xB6" G="0xB5" B="0xB5" />
    <Color x:Key="DarkerForegroundColor" A="0xFF" R="0x97" G="0x97" B="0x97" />
    <Color x:Key="DarkestForegroundColor" A="0xFF" R="0x76" G="0x76" B="0x76" />
    <Color x:Key="NormalBackgroundColor" A="0xFF" R="0x22" G="0x22" B="0x22" />
    <Color x:Key="DarkerBackgroundColor" A="0xFF" R="0x19" G="0x19" B="0x19" />
    <Color x:Key="LighterBackgroundColor" A="0xFF" R="0x33" G="0x33" B="0x33" />
     ....

為什么不能像下面所示的示例那樣直接使用資源字典中的顏色? 為簡單起見,我顯示的是“內聯”資源,而不是單獨的資源字典文件。 為什么需要在代碼中加載資源字典?

<Window.Resources>
    <x:Array x:Key="colors" Type="{x:Type Color}">
        <x:Static Member="Colors.White" />
        <x:Static Member="Colors.Red" />
        <x:Static Member="Colors.Green" />
        <x:Static Member="Colors.Blue" />
    </x:Array>
</Window.Resources>

<ListBox ItemsSource="{StaticResource colors}">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Rectangle Width="20" Height="20" Margin="2"
                        Stroke="Black">
                    <Rectangle.Fill>
                        <SolidColorBrush Color="{Binding}" />
                    </Rectangle.Fill>
                </Rectangle>
                <TextBlock Text="{Binding}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

如果您確實必須枚舉代碼中的資源,那么建議您在XAML中引用資源文件,並在后面的代碼中使用FrameworkElement.FindResource來保存數據。 在上面的特定示例中,代碼可能類似於:

 var colors = (IEnumerable) FindResource("colors");
 foreach(Color color in colors)
 {
    // Do something here...
 }

暫無
暫無

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

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