我必須使用以下方法從資源字典中使用指定的程序集和相對URI檢索對象Canvas
,並將Canvas
綁定到MenuItem
s Icon
。此代碼,以獲得矢量圖形Canvas
是正確綁定到畫布對象的大小圖標
public Canvas GetVectorGraphic(string assemblyName, string relativeUri, string name)
{
var imageResourceDictionary = new ResourceDictionary();
imageResourceDictionary.Source =
new Uri(assemblyName + ";component/" + relativeUri, UriKind.Relative)
?? new Uri(relativeUri, UriKind.Relative);
if (imageResourceDictionary.Source == null)
return default(Canvas);
return imageResourceDictionary[name] as Canvas;
}
我MenuItem
綁定是
<Style x:Key="MenuItem" TargetType="{x:Type Controls:MenuItemEx}">
<Setter Property="Icon">
<Setter.Value>
<Image Source="{Binding IconSource}" Width="16" Height="16"/>
</Setter.Value>
</Setter>
...
我也試圖
<Setter Property="Icon">
<Setter.Value>
<Rectangle Width="16" Height="16">
<Rectangle.Fill>
<VisualBrush Stretch="Uniform"
Visual="{Binding IconSource}"/>
</Rectangle.Fill>
</Rectangle>
</Setter.Value>
</Setter>
你可以看到,我都在嘗試將高度在Canvas
到16 x 16直接,也通過恢復填充大小的矩形,但這是失敗 - 它只是導致一個空白圖像。如果我忽略了Height
和Width
規範,則生成的圖形太大。
我也試圖調整Canvas
當我通過
...
Canvas c = imageResourceDictionary[name] as Canvas;
c.Height = 16;
c.Width = 16;
return c;
從詞典閱讀但這會造成圖像消失。
如何正確調整我的Canvas
對象以適合我的MenuItem
?
編輯(部分答案):
我來翻過很多很多帖子,但沒有就解決所有我在一個崗位有問題。問題:
- 未使用矢量圖形顯示任何圖像。 [已解決]
- 獲取圖像顯示但未正確縮放。 [求助]
- 獲取縮放和顯示的圖像,但一次只能顯示一個。 [求助]
- 圖像被縮放並顯示所有需要的MenuItems,但知道頂級菜單項有一個不需要的餘量。 [ON GOING]
我如何解決所有,但最後一個問題是1.使用正確的圖像源矢量圖形,在這種情況下,我發現填充矩形做了這項工作。 2.您可以直接綁定到Icon對象來獲取圖像,但是沒有真正的適當縮放這些圖像的方法。 3.您可以通過使用矩形縮放圖像,設置爲Width
和Height
並填充爲VisualBrush
,但這會在MenuItems
之間分配資源,因此只有一個會顯示出來。要使圖標不共享,您必須創建一個靜態資源並設置x:Shared="False"
。最終的XAML看起來像
<Rectangle x:Key="MenuItemIcon" x:Shared="False"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
Width="16" Height="16">
<Rectangle.Fill>
<VisualBrush Stretch="Uniform" Visual="{Binding IconSource}"/>
</Rectangle.Fill>
</Rectangle>
<Style x:Key="MenuItem" TargetType="{x:Type Controls:MenuItemEx}">
<Setter Property="Icon" Value="{StaticResource MenuItemIcon}"/>
<Setter Property="InputGestureText" Value="{Binding InputGestureText}"/>
<Setter Property="Caliburn:Action.Target" Value="{Binding}"/>
<Setter Property="Caliburn:Message.Attach" Value="{Binding ActionText}"/>
</Style>
突出問題
我現在已經在頂級項目也移動到右邊的問題(如圖中下方的紅色箭頭),因爲矩形的尺寸是硬編碼爲16。然而,結合Witdh
和Height
似乎會導致圖像再次消失......
我現在要嘗試到模板菜單項,並設置圖標區域自動合攏。任何其他的解決方案,歡迎...
看看[此觸發(http://pastebin.com/iM6agQ6j)在菜單項的風格幫你崩潰的空白。 – pushpraj 2014-09-21 12:20:41