[英]Changing Property of a Style Dynamically
我正在處理WPF應用程序。 我有一個資源字典,其中我為工具提示和按鈕編寫了自定義樣式。 實際上,對於按鈕,我有兩種樣式。 其中之一,包含了一個圖像,該圖像顯示在臀部的內容左側。
<Style x:Key="ButtonImageStyle" TargetType="{x:Type Button}">
........
<TextBlock Margin="5.25,2.417,5.583,5.25" Foreground = White />
<Image x:Name="ButtonImage" Source="/MyProject;component/Images/icoMainMenu01.png" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="-100,0,0,0" Width="16" Height="16"/>
.... </Style
現在,在MainWindow.xaml中,我具有以下內容:
<Button Style="{DynamicResource ButtonImageStyle}" x:Name="JustButton" Click="JustButton_Click" Height="50" ToolTip="Press for 1" Content="1" Margin="310,282,400,238" />
我希望能夠更改該圖像。 我將有8個按鈕,並且我希望每個按鈕都有與其相關的不同圖像。 你們有什么主意嗎? 謝謝!
有多種選擇,從(ab)使用Tag
類的屬性到UserControl
子類化或合成,您還可以創建一個附加屬性 。
最干凈的可能是子類化,然后您可以為要使用的ImageSource
創建一個新的依賴項屬性 ,然后可以使用TemplateBinding
將其綁定到默認TemplateBinding
。
要進行子類化,可以使用VS,從新項中選擇“ Custom Control (WPF)
,這將創建一個類文件,並將基本樣式添加到通常在Themes/Generic.xaml
找到的主題資源字典中。 該類如下所示:
//<Usings>
namespace Test.Controls
{
public class ImageButton : Button
{
public static readonly DependencyProperty ImageProperty =
DependencyProperty.Register("Image", typeof(ImageSource), typeof(ImageButton), new UIPropertyMetadata(null));
public ImageSource Image
{
get { return (ImageSource)GetValue(ImageProperty); }
set { SetValue(ImageProperty, value); }
}
}
}
現在,主題將變得更加復雜,您只需復制按鈕的默認模板之一,然后將其粘貼到默認樣式即可。 然后,您只需要將圖像添加到某處但具有此綁定:
<Image Source="{TemplateBinding Image}" .../>
使用此控件時,您將不再需要引用樣式,因為所有內容均為默認樣式,因此現在有了圖像的屬性:
<controls:ImageButton Content="Lorem Ipsum"
Image="Img.png"/>
(要使用Tag
您只需按一下普通按鈕,然后對標簽使用TemplateBinding,然后將按鈕的標簽設置為URL)
我忘了提到使用動態資源的另一種可能性,它有點冗長但非常簡單,請參閱我的答案作為示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.