将数据上下文字符串属性绑定到 StaticResource 键
我有一个带有 ResourceKey 和 Caption 的列表值,这些值都是字符串。 Resource是资源字典中定义的实际资源的名称。 这些 ResourceKey 图标中的每一个都是 Canvas 的。
<Data ResourceKey="IconCalendar" Caption="Calendar"/>
<Data ResourceKey="IconEmail" Caption="Email"/>
然后我有一个列表视图,其中有一个带有按钮的数据模板和按钮下方的文本标题。 我想要做的是将 Resource 静态资源显示为按钮的内容。
<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 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"/>
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.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
经过一番思考后,我最终使用了
ValueConvertor
,如下所示:按钮上的绑定变为
After having a little think I ending up using a
ValueConvertor
like so:and the binding on the button becomes
在这里,我得到了 @dvkwong 的答案的改进版本(以及 @Anatoliy Nikolaev 的编辑):
用法:
这里的主要更改是:
转换器现在是
System.Windows.Markup。 MarkupExtension
,因此可以直接使用,无需声明为资源。转换器是上下文感知的,因此它不仅会查找应用程序的资源,还会查找本地资源(当前窗口、用户控件或页面等)。
Here I've got an improved version of @dvkwong 's answer (along with @Anatoliy Nikolaev 's edit):
usage:
The primary change here is:
The converter is now a
System.Windows.Markup.MarkupExtension
so it can be used directly without being declared as a resource.The converter is context-aware, so it will not only look up in your App's resources, but also local resources (current window, usercontrol or page etc.).