将数据上下文字符串属性绑定到 StaticResource 键 [英] Binding a datacontext string property to a StaticResource key
问题描述
我有一个带有 ResourceKey 和 Caption 的 List 值,这些值都是字符串.Resource 是在资源字典中定义的实际资源的名称.这些 ResourceKey 图标中的每一个都是 Canvas 的.
I have an List values with a ResourceKey and a Caption, these values are both strings. The Resource is the name of an actual resource defined in a resource dictionary. Each of these ResourceKey Icons are Canvas's.
<Data ResourceKey="IconCalendar" Caption="Calendar"/>
<Data ResourceKey="IconEmail" Caption="Email"/>
然后我有一个列表视图,它有一个带有按钮的数据模板和按钮下方的文本标题.我想要做的是将Resource静态资源显示为按钮的内容.
I then have a list view which has a datatemplate with a button and a text caption below the button. What I want to do is display Resource static resource as the content for the button.
<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>
我想我已经尝试了绑定静态资源等的所有排列
I think I have tried every permutation with binding staticresource etc.
我对替代方案持开放态度,我知道只拥有一个图像并设置源属性可能更容易.
I am open to alternatives, I know it may be easier to just have an image and set the source property.
谢谢
推荐答案
在稍微思考之后我最终使用了一个 ValueConvertor
像这样:
After having a little think I ending up using a ValueConvertor
like so:
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}}" />
这篇关于将数据上下文字符串属性绑定到 StaticResource 键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!