gpt4 book ai didi

.net - 如何将样式应用于类及其后代?

转载 作者:行者123 更新时间:2023-12-04 14:51:53 25 4
gpt4 key购买 nike

我想将以下样式应用于所有源自 ButtonBase 的控件

<Style
TargetType="{x:Type ButtonBase}">
<Setter
Property="Cursor"
Value="Hand" />
</Style>

但它只适用于给定的类,而不适用于它的后代。如何实现我想要的?

最佳答案

这不起作用,因为当元素没有显式分配样式时,WPF 通过调用 FindResource 找到其样式。 ,使用元素的类型作为键。您已经创建了一个键为 ButtonBase 的样式的事实。没关系:WPF 找到键为 Button 的样式或 ToggleButton并使用它。

基于继承的查找方法将使用元素的类型查找样式,然后在未找到元素类型的样式时使用基类型(并继续进行直到找到样式或点击 FrameworkElement )。问题是只有在找不到匹配项时才有效 - 即如果 Button 没有默认样式,当然有。

你可以做两件事。一种是按照 Jens 的建议去做,使用样式的 BasedOn属性来实现您自己的样式层次结构。不过,这有点烦人,因为您必须为每种类型定义样式;如果不这样做,将使用该类型的默认 WPF 样式。

另一种方法是使用 StyleSelector实现此查找行为。像这样:

public class InheritanceStyleSelector : StyleSelector
{
public InheritanceStyleSelector()
{
Styles = new Dictionary<object, Style>();
}
public override Style SelectStyle(object item, DependencyObject container)
{
Type t = item.GetType();
while(true)
{
if (Styles.ContainsKey(t))
{
return Styles[t];
}
if (t == typeof(FrameworkElement) || t == typeof(object))
{
return null;
}
t = t.BaseType;
}
}

public Dictionary<object, Style> Styles { get; set; }
}

你可以创建一个实例,给它一组样式,然后将它附加到任何 ItemsControl :
<Window x:Class="StyleSelectorDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:StyleSelectorDemo="clr-namespace:StyleSelectorDemo" Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<StyleSelectorDemo:InheritanceStyleSelector x:Key="Selector">
<StyleSelectorDemo:InheritanceStyleSelector.Styles>
<Style x:Key="{x:Type ButtonBase}">
<Setter Property="ButtonBase.Background"
Value="Red" />
</Style>
<Style x:Key="{x:Type ToggleButton}">
<Setter Property="ToggleButton.Background"
Value="Yellow" />
</Style>
</StyleSelectorDemo:InheritanceStyleSelector.Styles>
</StyleSelectorDemo:InheritanceStyleSelector>
</Window.Resources>
<Grid>
<ItemsControl ItemContainerStyleSelector="{StaticResource Selector}">
<Button>This is a regular Button</Button>
<ToggleButton>This is a ToggleButton.</ToggleButton>
<TextBox>This uses WPF's default style.</TextBox>
</ItemsControl>
</Grid>
</Window>

关于.net - 如何将样式应用于类及其后代?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4278736/

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