WPF アプリケーションにはファイルが必要です。そこに、UI 全体で使用するApp.xaml
ファイルを追加できます。Styles
例:
<Application x:Class="WpfApplication8.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<Application.Resources>
<!--The style for all your buttons, setting the background property to your custom brush-->
<Style TargetType="{x:Type Button}"> <!--Indicate that this style should be applied to Button type-->
<Setter Property="Background">
<Setter.Value>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Black"/>
<GradientStop Color="White" Offset="1"/>
</LinearGradientBrush>
</Setter.Value>
</Setter>
</Style>
</Application.Resources>
</Application>
または、すべてのボタンに適用したくない場合は、UI の特定のボタンに適用できるようにStyle
aを指定できます。Key
<Application x:Class="WpfApplication8.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<Application.Resources>
<!--Add a x:Key value so you can use on certain Buttons not all-->
<Style x:Key="MyCustomStyle" TargetType="{x:Type Button}">
<Setter Property="Background">
<Setter.Value>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Black"/>
<GradientStop Color="White" Offset="1"/>
</LinearGradientBrush>
</Setter.Value>
</Setter>
</Style>
</Application.Resources>
</Application>
でこれを使用するStyle
にはButton
、バインディングを のStyle
プロパティに追加するだけです。Button
<Button Style="{StaticResource MyCustomStyle}" />
Style
これはちょうどこれに適用されますButton
または、本当にコード ビハインドで実行したい場合はBrush
、バックグラウンドに必要なものを追加するだけです
Button b = new Button
{
Background = new LinearGradientBrush(Colors.Black, Colors.White, new Point(0.5, 1), new Point(0.5, 0))
};
xaml は、上で投稿したコード ブラシのようにまったく同じプロパティ名を使用するため、xaml をコードに変換するのは非常に簡単です。
new LinearGradientBrush(Colors.Black, Colors.White, new Point(0.5, 1), new Point(0.5, 0))
は ....
Brush(firstColor,secondColor,StartPoint EndPoint)
Xaml はボタンのプロパティにアクセスするだけで、C# ではすべて同じ名前になります。