views:

346

answers:

1

Hi,

I have a WPF Datagrid binded with list of interface objects. Consider, ClsEmployee class implements I_Employee interface with properties Empl_Id, Empl_Name, Department, Address and City_name.

List _emplList;

consider, _emplList has 10 items.

dgEmployeeGrid.ItemsSource = _emplList;

Question: Now, if the user clicks on a button, then i should be able to read the City_name. Based on the City_name, i should be able to set the color (Color can be different for each row) for the rows dynamically through C# code.

Please help me how to do this?

Thanks in advance!

+1  A: 

Build a ValueConverter that takes in a "value" of the appropriate type in the grid, and then bind the Background color of the row to that field with the ValueConverter in there to provide the Color brush or whatever other kind of brush (that makes sense) that you'd like to put in there.

EDIT

Here is a Converter that converts a bool to a Brush color. This class has two properties called "True" and "False" which we set a Brush to that will be used when the boolean value matches the property. The converter is one way and does not convert brushes back to boolean values.

XAML to create instance of the Converter and set properties

<cga:BoolToBrushConverter x:Key="trueIsGreen" 
    True="Green" 
    False="Red"/>

C# Converter Code

[ValueConversion(typeof(bool), typeof(Brush))]
public class BoolToBrushConverter : IValueConverter
{
    public Brush True
    {
        get; set;
    }

    public Brush False
    {
        get; set;
    }

    public object Convert(object value, Type targetType, 
                          object parameter, CultureInfo culture)
    {
        if (targetType != typeof(Brush))
        {
            return null;
        }

        return ((bool) value) ? True : False;
    }

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

Example of binding value and convert to a field on an object that takes brushes

<Ellipse Width="10" Height="10" 
       Fill="{Binding Path=Reviewer.IsMentor, Mode=OneWay, 
                      Converter={StaticResource trueIsGreen}}"/>

I'm assuming you are familiar with databinding in WPF and won't elaborate that aspect of the solution but when the Reviewer.IsMentor is true, the Converter will provide a "Green" brush (sent when the Converter was created) to the Fill property of the ellipse.

Dave White
Hi Dave, I am quite new to WPF. Can you please provide some code?
ksvimal