wpf 将WebContext字符串属性绑定到StaticResource键

eivnm1vs  于 10个月前  发布在  其他
关注(0)|答案(2)|浏览(133)

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

<Data ResourceKey="IconCalendar" Caption="Calendar"/>
<Data ResourceKey="IconEmail" Caption="Email"/>

字符串
然后我有一个列表视图,其中有一个数据模板,按钮和按钮下面的文本标题。我想做的是显示资源静态资源作为按钮的内容。

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


我想我已经尝试了绑定静态资源等的每一种排列。
我对替代方案持开放态度,我知道只需要一个图像并设置源属性可能会更容易。
谢谢

3hvapo4f

3hvapo4f1#

经过一点思考,我最终使用了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.");
    }
}

字符串
纽扣上的约束力

<Button Content="{Binding ResourceKey, Converter={StaticResource resourceConverter}}" />

pcrecxhr

pcrecxhr2#

这里我有一个改进版的@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;
    }
}

字符串
使用方法:

<Button Content="{Binding ResourceKey, Converter={design:StaticResourceConverter}}" />


这里的主要变化是:
1.转换器现在是System.Windows.Markup.MarkupExtension,因此可以直接使用,而无需声明为资源。
1.转换器是上下文感知的,因此它不仅会查找应用程序的资源,而且还会查找本地资源(当前窗口,用户控件或页面等)。

相关问题