将datacontext字符串属性绑定到StaticResource键

dvk*_*ong 8 data-binding wpf binding static-resource

我有一个带有ResourceKey和Caption的List值,这些值都是字符串.资源是资源字典中定义的实际资源的名称.这些ResourceKey图标中的每一个都是Canvas的.

<Data ResourceKey="IconCalendar" Caption="Calendar"/>
<Data ResourceKey="IconEmail" Caption="Email"/>
Run Code Online (Sandbox Code Playgroud)

然后我有一个列表视图,其中有一个带按钮的datatemplate和按钮下方的文本标题.我想要做的是显示资源静态资源作为按钮的内容.

<ListView.ItemTemplate>
    <DataTemplate>
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="*" />
                <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>

            <Button Content="{Binding ResourceKey}" Template="{StaticResource  RoundButtonControlTemplate}"/>
            <TextBlock Grid.Row="1" Margin="0,10,0,0" Text="{Binding Caption}" HorizontalAlignment="Center" FontSize="20" FontWeight="Bold" />
        </Grid>
    </DataTemplate>
</ListView.ItemTemplate>
Run Code Online (Sandbox Code Playgroud)

我想我已尝试使用绑定staticresource等进行每个排列.

我对替代方案持开放态度,我知道拥有一个图像并设置source属性可能更容易.

谢谢

dvk*_*ong 11

稍微想一想我最终使用了ValueConvertor这样的:

class StaticResourceConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var resourceKey = (string)value;

        return Application.Current.Resources[resourceKey];
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new Exception("The method or operation is not implemented.");
    }
}
Run Code Online (Sandbox Code Playgroud)

并且按钮上的绑定变为

<Button Content="{Binding ResourceKey, Converter={StaticResource resourceConverter}}" />
Run Code Online (Sandbox Code Playgroud)


hil*_*lin 7

在这里,我得到了 @dvkwong 答案的改进版本(以及 @Anatoliy Nikolaev 的编辑):

class StaticResourceConverter : MarkupExtension, IValueConverter
{
    private Control _target;


    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var resourceKey = (string)value;

        return _target?.FindResource(resourceKey) ?? Application.Current.FindResource(resourceKey);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        var rootObjectProvider = serviceProvider.GetService(typeof(IRootObjectProvider)) as IRootObjectProvider;
        if (rootObjectProvider == null)
            return this;

        _target = rootObjectProvider.RootObject as Control;
        return this;
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

<Button Content="{Binding ResourceKey, Converter={design:StaticResourceConverter}}" />
Run Code Online (Sandbox Code Playgroud)

这里的主要变化是:

  1. 转换器现在是 aSystem.Windows.Markup.MarkupExtension因此它可以直接使用而无需声明为资源。

  2. 转换器是上下文感知的,因此它不仅会在您的应用程序资源中查找,还会在本地资源(当前窗口、用户控件或页面等)中查找。