「○○をコードで設定する」シリーズで Style を扱っていなかったので、今更ですがエントリ。
例えば TextBox 用の Style は XAML で
<Style x:Key="{x:Type TextBox}" TargetType="{x:Type TextBox}"> <Setter Property="Background" Value="Yellow"/> <Setter Property="Foreground" Value="Blue"/> <Setter Property="Width" Value="180"/> <Setter Property="Height" Value="30"/> </Style>
と書けます。これを C# のコードで書くと
Style style = new Style(typeof(TextBox)); // 依存プロパティ識別用のフィールドを使って設定する。 style.Setters.Add(new Setter(TextBox.WidthProperty, 180.0)); style.Setters.Add(new Setter(TextBox.HeightProperty, 30.0)); style.Setters.Add(new Setter(TextBox.BackgroundProperty, new SolidColorBrush(Colors.Yellow))); style.Setters.Add(new Setter(TextBox.ForegroundProperty, new SolidColorBrush(Colors.Blue)));
となります。簡単。
前に画面を全てコードで作成したとき、Tips の形でエントリを書いておけばよかったな。