繁体   English   中英

如何使用XAML将资源添加到控件中,类似于ctrl.Resources.Add()

[英]How to add Resources to a control with XAML, similar to 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中有没有办法做到这一点?

您无需在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

尝试这个:

<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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM