0

目前,我可以使用类似于以下内容的控件向控件添加资源:

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 中做到这一点?

4

2 回答 2

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}" />

或者它在一个非静态对象中,你需要使用Binding和一个IValueConverter资源名称为ConverterParameter.

于 2012-07-12T11:25:57.903 回答
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>
于 2012-07-12T11:30:12.280 回答