gpt4 book ai didi

c# - 提取相同的属性以在 WPF XAML 中设置样式

转载 作者:行者123 更新时间:2023-11-30 21:56:06 27 4
gpt4 key购买 nike

我无法将一些属性提取到我的 Xaml 文件中的元素样式。我有很多重复的 block ,例如:

<controls:RoundableToggleRadioButton Style="{StaticResource RoundableToggleRadioButtonStyle}">
<StackPanel>
<Image Width="32"
Margin="2"
Source="Images/inbox_upload.png" />
<TextBlock Margin="2"
Foreground="White"
Text="Extract"
TextAlignment="Center" />
</StackPanel>

所以我想为每个按钮提取相同的属性以设置样式并能够更改图像和文本。像这样:

<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<StackPanel>
<Image Width="32"
Margin="2" />
<TextBlock Margin="2"
Foreground="White"
TextAlignment="Center" />
</StackPanel>
</DataTemplate>
</Setter.Value>

<controls:RoundableToggleRadioButton Style="{StaticResource RoundableToggleRadioButtonStyle}">
<StackPanel>
<Image Source="Images/inbox_upload.png" />
<TextBlock Text="Extract"/>
</StackPanel>

那有可能吗?或者有一些解决方法?感谢您的帮助)))

最佳答案

创建继承Button的新类

public class ImageTextButton : Button
{
public static readonly DependencyProperty IconProperty =
DependencyProperty.Register("Icon", typeof (ImageSource), typeof (ImageTextButton), null);

public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof (string), typeof (ImageTextButton), null);

public ImageTextButton()
{
this.DefaultStyleKey = typeof(ImageTextButton);
}

public ImageSource Icon
{
get { return (ImageSource) GetValue(IconProperty); }
set { SetValue(IconProperty, value); }
}

public string Text
{
get { return (string) GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
}

xaml

<Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wpfApplication3="clr-namespace:WpfApplication3"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Style TargetType="{x:Type wpfApplication3:ImageTextButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type wpfApplication3:ImageTextButton}">
<StackPanel Height="Auto" Orientation="Horizontal">
<Image Source="{TemplateBinding Icon}" Stretch="Fill"/>
<TextBlock Text="{TemplateBinding Text}"/>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<wpfApplication3:ImageTextButton Text="Submit" Icon="Hydrangeas.jpg"></wpfApplication3:ImageTextButton>
</Grid>

除了创建新的 Text 属性,您还可以使用 Button 的 Content 属性。

关于c# - 提取相同的属性以在 WPF XAML 中设置样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31717979/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com