質問
2018年4月23日月曜日 12:51
いつもお世話になっております。
現在、C#/WPFでアプリケーションの開発を行っております。
Styleの共通化について質問させていただきます。
以下のようなXAMLアプリケーションがあったとします。
<Window x:Class="WpfApplication1.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">
<Grid>
<StackPanel>
<TextBox Text="{Binding Text1}"/>
<Label x:Name="Label1">
<Label.Style>
<Style TargetType="Label">
<Style.Triggers>
<DataTrigger Binding="{Binding Text1}" Value="{x:Null}">
<Setter Property="Background" Value="Red"/>
<Setter Property="Foreground" Value="Black"/>
<Setter Property="Opacity" Value="0.5"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Label.Style>
</Label>
<TextBox Text="{Binding Text2}"/>
<Label x:Name="Label2">
<Label.Style>
<Style TargetType="Label">
<Style.Triggers>
<DataTrigger Binding="{Binding Text2}" Value="{x:Null}">
<Setter Property="Background" Value="Red"/>
<Setter Property="Foreground" Value="Black"/>
<Setter Property="Opacity" Value="0.5"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Label.Style>
</Label>
</StackPanel>
</Grid>
</Window>
Label1とLabel2では、それぞれDataTriggerを使って動的にUIの表示変更を行っています。
ただし、このStyleはBinding先が異なるだけで他の点は同じ設定になっています。
このようなケースでは、ResourceDictionaryなどにStyleとして切り出して、Binding先だけを切り替えるといったようなことは可能でしょうか?
[開発環境]
OS : Windows10 x64
IDE : Visual Studio 2010
言語:C# / WPF
すべての返信 (2)
2018年4月23日月曜日 15:43 ✅回答済み | 1 票
Tag経由でもいいなら
<Window x:Class="WpfApplication1.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>
<Style TargetType="{x:Type Label}" x:Key="testLabelStyle">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=Tag,RelativeSource={RelativeSource Mode=Self}}" Value="{x:Null}">
<Setter Property="Background" Value="Red"/>
<Setter Property="Foreground" Value="Black"/>
<Setter Property="Opacity" Value="0.5"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<StackPanel>
<TextBox Text="{Binding Text1}" />
<Label x:Name="Label1" Content="らべる1"
Style="{StaticResource testLabelStyle}"
Tag="{Binding Path=Text1}"/>
<TextBox Text="{Binding Text2}" x:Name="textBxox2"/>
<Label x:Name="Label2" Content="らべる2"
Style="{StaticResource testLabelStyle}"
Tag="{Binding Path=Text2}"/>
</StackPanel>
</Grid>
</Window>
個別に明示されていない限りgekkaがフォーラムに投稿したコードにはフォーラム使用条件に基づき「MICROSOFT LIMITED PUBLIC LICENSE」が適用されます。(かなり自由に使ってOK!)
2018年4月24日火曜日 13:10
ご回答ありがとうございます。
Tagに;納して、Binding先を共通化させるということですね。
参考にさせていただきます!