简体   繁体   中英

Style based on property value

I am trying to style communication module of my app. I am getting the some data from extenal API which are bound inside DataTemplate. I would like to change ListView ItemTemplate style based on value of Status property.

If the status is "new" then the border of the grid should be 2px Orange, if the status is "read" then the border of the grid should be 1px Gray.

I have achieved this using converters but I bet there is better way.

XAML file

<ListView ItemsSource="{Binding ConversationsList}">
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <Setter Property="Padding" Value="0,0,0,0"/>
            <Setter Property="Margin" Value="0,0,0,0"/>
        </Style>
    </ListView.ItemContainerStyle>
    <ListView.ItemTemplate>
        <DataTemplate>
            <Grid BorderBrush="{Binding status, Converter={StaticResource StatusToBorder}, ConverterParameter=BorderBrush}"  
                  BorderThickness="{Binding status, Converter={StaticResource StatusToBorder}, ConverterParameter=BorderThickness}"
                  Background="White"
                  Margin="5,5,5,5">

Converter File

class StatusToBorder : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        var param = parameter as String;
        var _value = value as String;
        switch (param) {
            case "BorderBrush":
                if (_value == "new")
                    return "#FFFF5917";
                else
                    return "#FFAAAAAA";
            case "BorderThickness":
                if (_value == "new")
                    return new Thickness(2, 2, 2, 2);
                else
                    return new Thickness(1, 1, 1, 1); ;
            default:
                return null;
                break;
        }
    }



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

You need to give the Grid a name in xaml. In xaml:

<Grid  x:Name=MyGrid 
  IsRead="{Binding Read}"...>

Then within your code where the grid is marked as read or not:
In Java:

MyGrid.BorderBrush = new SolidColorBrush(Windows.UI.Colors.Orange);
MyGrid.BorderThickness = new Thickness(3);

MyGrid.BorderBrush = new SolidColorBrush(Windows.UI.Colors.Gray);
MyGrid.BorderThickness = new Thickness(1);

I'm assuming you know how to set the datacontext, and resources, etc. If not, this tut covers the data binding more thoroughly:
https://msdn.microsoft.com/en-us/library/windows/apps/jj207023(v=vs.105).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM