C# 使用样式时传递值
我有一个C# 使用样式时传递值,c#,wpf,xaml,C#,Wpf,Xaml,我有一个按钮样式: <Style TargetType="{x:Type Button}" x:Key="myBtnStyle"> <Setter Property="ContentTemplate"> <Setter.Value> <DataTemplate> <Grid> <Grid.RowDefinitio
按钮
样式:
<Style TargetType="{x:Type Button}" x:Key="myBtnStyle">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0"
x:Name="myTextBlock" />
<Rectangle Grid.Row="1"
x:Name="myRectangle" />
</ close everything>
如果我不能在那里分配,那么我可以在哪里分配 在此处使用
按钮.Template
(ControlTemplate
)可能比使用按钮更容易。ContentTemplate
(DataTemplate
):
然后,您可以对按钮已有的属性使用
TemplateBinding
,例如,对文本使用button.Content
,对填充使用button.Background
<Style TargetType="{x:Type Button}" x:Key="myBtnStyle" >
<Setter Property="Template" >
<Setter.Value>
<ControlTemplate TargetType="Button" >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Text="{TemplateBinding Content}" />
<Rectangle Grid.Row="1" Fill="{TemplateBinding Background}" />
</ close everything>
用法:
<Button Style="{StaticResource ResourceKey=myBtnStyle}"
Content="My text here.." Background="Blue"
Click="myBtn_Click" />
<Button Style="{StaticResource ResourceKey=myBtnStyle}"
Content="My text 1" Tag="http://programming.enthuses.me/1.png" />
<Button Style="{StaticResource ResourceKey=myBtnStyle}"
Content="My text 2" Tag="/MyIcons/Icon01.png" />
<Button Style="{StaticResource ResourceKey=myBtnStyle}"
Content="My text here.." Background="Blue"
Click="myBtn_Click" />
如前所述,您可以使用
TemplateBinding
,这是一种书写的简写:
{Binding Path=Content, RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type Button}}}
在您的情况下,代码是:
<TextBlock Text="{TemplateBinding Content}" />
<Rectangle Width="50" Height="10" Fill="{TemplateBinding Button.Background}" />
用法:
<Button Style="{StaticResource ResourceKey=myBtnStyle}"
Content="My text here.." Background="Blue"
Click="myBtn_Click" />
<Button Style="{StaticResource ResourceKey=myBtnStyle}"
Content="My text 1" Tag="http://programming.enthuses.me/1.png" />
<Button Style="{StaticResource ResourceKey=myBtnStyle}"
Content="My text 2" Tag="/MyIcons/Icon01.png" />
<Button Style="{StaticResource ResourceKey=myBtnStyle}"
Content="My text here.." Background="Blue"
Click="myBtn_Click" />
如果按钮的内容和背景未被使用,则可以使用templatebinding!但是如果不是矩形
,而是图像
。如何在此处绑定图像源代码
?一个简单的解决方案是对图像的源代码使用通用的按钮.Tag
。我在回答中加了一个例子。当然,只有一个标记
属性,因此如果您需要其他信息,并且按钮
上没有合适的属性,您可以通过创建自己的自定义来添加自定义内容,或者创建自己的按钮
子类。