当前位置:网站首页>Assign a dynamic value to the background color of DataGrid through ivalueconverter

Assign a dynamic value to the background color of DataGrid through ivalueconverter

2022-07-07 14:12:00 Peacock Flying Southeast - Shenzhen

1 Create a class

    public class A
    {
        private string _result;

        public string Result
        {
            get { return _result; }
            set { _Title = result; }
        }
    }

2 Create a ColorConverter class Inherited from IValueConverter class

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            //throw new NotImplementedException();

            if(value as string == "Success")
            {
                return "Green";
            }
            else
            {
                return "Red";
            }

        }

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

3 stay   xaml Written in a file :

<Window.Resources>
     <local:ColorConverter x:Key="MyColorConvert"/>
</Window.Resources>

4 stay  <DataGrid.Columns> It's written inside :

<DataGridTemplateColumn Width="150" >
                    
    <DataGridTemplateColumn.HeaderTemplate>
          <DataTemplate>
                 <TextBlock Text="Result" />
          </DataTemplate>
    </DataGridTemplateColumn.HeaderTemplate>

    <!-- Column content -->
    <DataGridTemplateColumn.CellTemplate>
          <DataTemplate>
               <TextBlock Text="{Binding Result}" 
                        VerticalAlignment="Center"
                        HorizontalAlignment="Center" 
                        Background="{Binding Result,Converter={StaticResource MyColorConvert}}"/>
          </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

5 Write... In the main function :

private List<A> _con;

public List<A> Con
{
      get { return _con; }
      set { _con = value; }
}

6 stay mainwindow Write :

if(Con == null)
{
      Con = new List<A>();
      Con.Add(new A()
      {
            Result = "Success";
      });

      Con.Add(new A()
      {
            Result = "Fail";
      });

      dataGrid.ItemsSource = Con;
}

7 design sketch :

 

 

 

 

 

原网站

版权声明
本文为[Peacock Flying Southeast - Shenzhen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071209532979.html