これにはRowStyleSelectorを使用してみます。さまざまな行スタイルを定義し、その行のデータに応じて行ごとに 1 つを選択できます。
基本的に、 を継承するクラスを定義しStyleSelector
、メソッドをオーバーライドしますSelectStyle
。行データに基づいてスタイルを選択するロジックを配置する場所です。行データitem
が含まれています。
public class MyStyleSelector : StyleSelector
{
public override Style SelectStyle(object item, DependencyObject container)
{
if (item is Customer)
{
return ((Customer)item).IsComplete ?
App.Current.Resources["RedRowStyle"] :
App.Current.Resources["NormalRowStyle"]
}
return base.SelectStyle(item, container);
}
}
リソースをアプリケーションのリソース ディクショナリに追加します。
<Application.Resources>
<Style TargetType="DataGridRow" x:Key="NormalRowStyle">
</Style>
<Style TargetType="DataGridRow" BasedOn="{StaticResource NormalRowStyle}" x:Key="RedRowStyle">
<Setter Property="Background" Value="Red" />
</Style>
</Application.Resources>
次に、次のような静的リソースを介してセレクターを参照します。
<Window>
<Window.Resources>
<local:MyStyleSelector x:Key="MyStyleSelector" />
</Window.Resources>
<DataGrid RowStyleSelector="{StaticResource MyStyleSelector}">
<!-- ... -->
</DataGrid>
</Window>