WPF项目设置控件默认样式
- 新建一个资源字典,定义控件样式。
例如设置Textbox文本竖直方向上居中:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style TargetType="{x:Type TextBox}">
<Setter Property="VerticalContentAlignment" Value="Center"></Setter>
</Style>
</ResourceDictionary>
将其保存到“Themes/ControlsStyles.xaml”
2. 在 App.xaml 中引用。
如果你希望这个样式 全局生效(整个项目都用),在 App.xaml 的 Application.Resources 里合并:
<Application x:Class="YourNamespace.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<!-- 引用你的资源字典 -->
<ResourceDictionary Source="Themes/ControlsStyles.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
- 在窗口或控件中单独引用
如果只想在某个 Window 或 UserControl 中生效:
<Window x:Class="YourNamespace.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Themes/ControlsStyles.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Grid>
<!-- 你的控件 -->
</Grid>
</Window>
781

被折叠的 条评论
为什么被折叠?



