這不是MahApps.Metro特定的,但恰好是我正在使用的。我有一組ViewModel,它們具有string
屬性,表示從資源XAML文件使用哪個圖標。如何爲DynamicResource使用ViewModel變量?
public class CommandViewModel : ViewModel
{
public CommandViewModel(string displayName, ICommand command, string icon)
{
if (command == null)
throw new ArgumentNullException("command");
DisplayName = displayName;
Command = command;
Icon = icon;
}
public ICommand Command { get; private set; }
public string Icon { get; set; }
}
Icon
將結束是像從MahApps.Metro.Resources 「appbar_add」。這些在Icons.xaml文件中定義。
如何在我的ItemTemplate
中編寫此代碼,以便顯示正確的資源。我要麼執行時出錯(不是編輯/編譯),要麼我沒有任何圖標。
「無圖標」 XAML看起來像這樣:
<ItemsControl ItemsSource="{Binding}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Rectangle Width="20" Height="20">
<Rectangle.Fill>
<VisualBrush Visual="{DynamicResource {Binding Path=Icon}}" />
</Rectangle.Fill>
</Rectangle>
<TextBlock Margin="15,6">
<Hyperlink Command="{Binding Path=Command}">
<TextBlock Text="{Binding Path=DisplayName}" />
</Hyperlink>
</TextBlock>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
我嘗試導致錯誤使用StaticResource
,我認爲這是不正確根本。
我該如何引用Icon
屬性作爲我想要的資源的名稱?請求
編輯
更多的代碼,所以這裏是一個什麼樣做工作的一個例子:
<Rectangle Width="20" Height="20">
<Rectangle.Fill>
<VisualBrush Visual="{StaticResource appbar_add}" />
</Rectangle.Fill>
</Rectangle>
我需要做的是讓什麼「appbar_add」是一個值從屬性在我的ViewModel - 上面的Icon
屬性。
的資源是在一個單獨的文件(Icon.xaml)ResourceDictionary中,看起來像以下:
<Canvas x:Key="appbar_add" Width="76" Height="76" Clip="F1 M 0,0L 76,0L 76,76L 0,76L 0,0">
<Path Width="38" Height="38" Canvas.Left="19" Canvas.Top="19" Stretch="Fill" Fill="{DynamicResource BlackBrush}" Data="F1 M 35,19L 41,19L 41,35L 57,35L 57,41L 41,41L 41,57L 35,57L 35,41L 19,41L 19,35L 35,35L 35,19 Z "/>
</Canvas>
有用的鏈接:http://stackoverflow.com/questions/20564862/binding-to-resource-key-wpf – dugas 2015-04-01 17:59:11