你可以實現兩個附加屬性 - 一個用於Image
源和一個文本 - 你可以在任何Button
設置:
public class ButtonProperties
{
public static readonly DependencyProperty ImageSourceProperty =
DependencyProperty.RegisterAttached("ImageSource", typeof(Uri), typeof(ButtonProperties));
public static Uri GetImageSource(Button button)
{
return (Uri)button.GetValue(ImageSourceProperty);
}
public static void SetImageSource(Button button, Uri value)
{
button.SetValue(ImageSourceProperty, value);
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.RegisterAttached("Text", typeof(Uri), typeof(ButtonProperties));
public static string GetText(Button button)
{
return (string)button.GetValue(ImageSourceProperty);
}
public static void SetText(Button button, string value)
{
button.SetValue(ImageSourceProperty, value);
}
}
然後你只需要定義一次ContentTemplate
作爲一種資源,例如,在您的App.xaml:
<Application x:Class="WpfApplication1.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
StartupUri="MainWindow.xaml">
<Application.Resources>
<DataTemplate x:Key="dataTemplate">
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Path=(local:ButtonProperties.ImageSource), RelativeSource={RelativeSource AncestorType=Button}}" Height="20"/>
<TextBlock Text="{Binding Path=(local:ButtonProperties.Text), RelativeSource={RelativeSource AncestorType=Button}}" Margin="5,0,0,0"/>
</StackPanel>
</DataTemplate>
</Application.Resources>
</Application>
用法:
<Button local:ButtonProperties.Text="Staff"
local:ButtonProperties.ImageSource="pack://application:,,,/Resources/MainWindowIcons/Staff.ico"
ContentTemplate="{StaticResource dataTemplate}" />
來源
2017-02-23 16:41:19
mm8
您還不更改TextBlock的Text屬性? – Clemens
試試這樣。
Praveen
檢查此帖:http://stackoverflow.com/questions/34182134/wpf-how-to-pass-content-property-between-styles-and-controltemplate –