2012-07-12 103 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