這可以通過數據綁定來完成,但它是最好使用一個屬性界面,讓您可以簡單地輸入類似:
<local:OptionControl Text="Status wijzigen" ImageSource="/UserControlSolution;component/Image/user.png" />
這樣你就不需要在單獨的數據層中有你的UI標籤和圖標。
這可以通過創建一個控件類來實現,該控件類定義了Dependency Properties,並使用TemplateBindings在ControlTemplate中綁定了它們。
現有的控件可能具有適當的屬性,您可以爲其創建模板。這HeaderedContentControl模板應該爲你工作,雖然一個自定義的控制會更好:
<Style x:Key="HeaderedContentControlStyle" TargetType="HeaderedContentControl">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="HeaderedContentControl">
<Grid Style="{StaticResource MenuItemGridStyle}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="30" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Style="{StaticResource MenuItemTextblockStyle}" Text="{TemplateBinding Header}" />
<Image Grid.Column="1" Source="{TemplateBinding Content}" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
用法:
<HeaderedContentControl Name="OptionChangeUserState" Grid.Row="0"
Style="{StaticResource HeaderedContentControlStyle}"
Header="Status wijzigen">
<BitmapImage>/UserControlSolution;component/Image/user.png</BitmapImage>
</HeaderedContentControl>
請注意,我們需要包裝在BitmapImage
圖像路徑明確。這是因爲HeaderedContentControl.Content
屬性未聲明爲圖像類型,所以WPF不會自動將其轉換。
+1對於'Tag'屬性的有趣使用。 – Sheridan
謝謝@Sheridan :) – Nitin