2012-07-12 21 views
0

目前,我可以添加資源控制類似下面的內容控制:如何將資源添加到與XAML,類似於ctrl.Resources.Add()

Button b = new Button(); 
b.Resources.Add("item", currentItem); 

我想要做的這與XAML。我試過類似

<Button Content="Timers Overview" Name="btnTimerOverview"> 
    <Button.Resources> 
     <ResourceDictionary> 
      <!-- not sure what to add here, or if this is even correct -->    
      <!-- I'd like to add something like a <string, string> mapping -->    
      <!-- like name="items" value="I am the current item." --> 
     </ResourceDictionary> 
    </Button.Resources> 
</Button> 

但我沒有得到任何進一步的比這。有沒有辦法在XAML中做到這一點?

+0

什麼是你想用資源來實現呢? – 2012-07-12 11:23:39

+0

基本上我試圖將一個值與可以映射到系統外部的另一個配置文件的控件相關聯。當控件加載時,我可以讀取作爲資源存儲的該值,並根據該值從外部配置中獲取配置。 – binncheol 2012-07-12 11:25:38

回答

1

試試這個:

<Window x:Class="ButtonResources.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525" 
     xmlns:system="clr-namespace:System;assembly=mscorlib" 
     > 
    <Grid> 
     <Button Content="Timers Overview" Name="btnTimerOverview"> 
      <Button.Resources> 
       <ResourceDictionary> 
        <!-- not sure what to add here, or if this is even correct --> 
        <!-- I'd like to add something like a <string, string> mapping --> 
        <!-- like name="items" value="I am the current item." --> 
        <system:String x:Key="item1">Item 1</system:String> 
        <system:String x:Key="item2">Item 2</system:String> 
       </ResourceDictionary> 
      </Button.Resources> 
     </Button> 
    </Grid> 
</Window> 
+0

看起來像什麼是理想的,但類型系統:字符串未找到。 – binncheol 2012-07-12 11:31:10

+1

您必須添加命名空間:xmlns:system =「clr-namespace:System; assembly = mscorlib」 – kmatyaszek 2012-07-12 11:31:49

3

你並不需要定義下Button.Resources ResourceDictionary中

你可以只添加任何一種資源的這樣的:

<Button Content="Timers Overview" Name="btnTimerOverview"> 
    <Button.Resources> 
     <!--resources need a key --> 
     <SolidColorBrush x:Key="fontBrush" Color="Blue" /> 
     <!--But styles may be key-less if they are meant to be "implicit", 
      meaning they will apply to any element matching the TargetType. 
      In this case, every TextBlock contained in this Button 
      will have its Foreground set to "Blue" --> 
     <Style TargetType="TextBlock"> 
      <Setter Property="Foreground" Value="{StaticResource fontBrush}" /> 
     </Style> 
     <!-- ... --> 
     <sys:String x:Key="myString">That is a string in resources</sys:String> 
    </Button.Resources> 
</Button> 

隨着sys被映射爲:

xmlns:sys="clr-namespace:System;assembly=mscorlib" 

現在,我想我明白你想要從某些應用程序設置/配置中加載字符串:它不是常量。

對於這一點,這是一個有點棘手:
要麼你有可用的字符串靜態,然後你可以這樣做:

<TextBlock Text="{x:Static local:MyStaticConfigClass.TheStaticStringIWant}" /> 

,或者它在非靜態的對象,你將需要使用BindingIValueConverter,資源名稱爲ConverterParameter

+0

這不是我想要做的。我想結合例如與控件的任意字符串值,而不是樣式或畫筆。 – binncheol 2012-07-12 11:30:00

+0

所以只需添加一個字符串和一個鍵。我將添加字符串示例。 – 2012-07-12 11:30:33