我是wpf的新手,我想使用样式和className.property
该样式不适用于第一个文本框
事实上它适用于堆栈面板
我错过了什么吗?
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="883">
<Grid>
<Grid.Resources >
<Style x:Key="m">
<Setter Property="TextBox.Background" Value="Aqua"/>
</Style>
</Grid.Resources>
<TextBlock >adsdfsadfasdfad</TextBlock>
<StackPanel Orientation="Horizontal" Style="{StaticResource m}">
<TextBox HorizontalAlignment="Stretch" Width="193" Margin="50">
</TextBox>
<TextBox HorizontalAlignment="Stretch" Width="193" Background="Black" Margin="50">
</TextBox>
</StackPanel>
</Grid>
看一下this文章 在那里找到Property =“ClassName.Property” 谢谢。
答案 0 :(得分:2)
如果您想要在堆栈面板中为所有TextBox设置样式,请尝试使用
<Grid>
<Grid.Resources >
<Style x:Key="m" TargetType="{x:Type TextBox}">
<Setter Property="Background" Value="Blue" />
</Style>
</Grid.Resources>
<TextBlock >adsdfsadfasdfad</TextBlock>
<StackPanel Orientation="Horizontal" >
<StackPanel.Resources>
<Style BasedOn="{StaticResource m}" TargetType="{x:Type TextBox}" />
</StackPanel.Resources>
<TextBox HorizontalAlignment="Stretch" Name="ss" Width="193" Margin="50"/>
<TextBox Width="193" Margin="50"/>
</StackPanel>
</Grid>
您可以使用TargetType="{x:Type TextBox}
答案 1 :(得分:1)
所以这是另一个更好地理解setter如何工作的例子:
<Window.Resources>
<Style x:Key="m">
<Setter Property="TextBox.Height"
Value="100" />
</Style>
</Window.Resources>
<Grid>
<StackPanel Style="{StaticResource m}">
<TextBlock>My Sample</TextBlock>
<TextBox>My text box</TextBox>
</StackPanel>
</Grid>
这里,TextBox.Height不是指TextBox的高度,而只是指向一个名为Height的依赖属性。此行为是由于样式没有TargetType。 因此,在此示例中,文本框的高度将保留为默认值,并且只有stackpanel的高度将更改为100.
类似的事情也发生在FontFamily的例子中。实际发生的是setter将StackPanel FontFamiliy属性设置为setter中的值。另外要记住的一件事是,父控件和它们的子控件之间会继承一些属性。 但是你需要小心,因为不继承属性。例如,FontFamily没问题,但TextBox控件不会继承Foreground。
我认为你可以使用像
这样的唯一方法Property = "ClassName.Property"
是要应用该样式的控件的可视树包含ClassName类型的元素。
例如
<Window.Resources>
<Style x:Key="m">
<Setter Property="TextBlock.FontFamily"
Value="Aharoni" />
</Style>
</Window.Resources>
<Grid>
<StackPanel Style="{StaticResource m}">
<TextBlock>My Sample</TextBlock>
</StackPanel>
</Grid>
这里StackPanel在其可视树中包含一个TextBlock,因此现在将把setter应用于它。
此外,如果您在样式中定义TargetType,它将知道应用模板的控件。
Here是一个描述控件的可视树的链接。