结合一个属性串财产的一个关键示
-
22-08-2019 - |
题
我有一个列表的价值观与ResourceKey和一个标题,这些价值观是这两个串。资源是名称的实际定义的资源在资源的字典。每个这些ResourceKey标画布上的。
<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>
我认为我已经试过每一个置换具有约束力的示等。
我是开放的替代办法,我知道它可能更易于只有一个图像并设定源的财产。
感谢
解决方案
具有小认为我结束了使用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}}" />
其他提示
我在这里已经有了一个改进版的@dvkwong's答复(与@阿纳托利尼古拉耶夫's编辑):
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}}" />
主要变化是:
转换器是现在
System.Windows.Markup.MarkupExtension
所以它可以直接使用没有被宣布作为一种资源。转换器是下意识的,因此,它将不仅要看在你的应用程序的资源,而且当地资源(前的窗口,用户控件或网页等)。
不隶属于 StackOverflow