سؤال

I added a style in my StandardStyles.xaml that is defined like this:

        <TextBlock Name="txtStatus" Text="{Binding Status}" 
               Margin="10,2,0,0" Width="350" TextTrimming="WordEllipsis"/>

The displayed text will then depend on the Status property on the bound data source. I would like to include the Word "Status:" before so that the final would be like this: "Status: Complete".

I would also like to have a conditional color depending on the status. In the above case, I would like Completed to be green (Status word would still be the normal color).

How can I do that?

هل كانت مفيدة؟

المحلول

For conditional styling you have to use data binding converter. First of all create a new class like given below.

public class StatusToColorConverter : IValueConverter
{

    public object Convert(object value, Type targetType, object parameter, string language)
    {
        var _status = value.ToString();
        if (_status == "To Do")
            return new SolidColorBrush(Windows.UI.Colors.Red);
        else if (_status == "In Progress")
            return new SolidColorBrush(Windows.UI.Colors.Yellow);
        else if (_status == "Completed")
            return new SolidColorBrush(Windows.UI.Colors.Green);
        else
            return new SolidColorBrush(Windows.UI.Colors.White);
    }

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

Now when you want to use, add it as page's resource like this

<Page.Resources>
    <local:StatusToColorConverter x:Key="StatusToColor"/>
</Page.Resources>

And then you have to use that that converter in TextBlock's foreground property which is bound by Status. It will return appropriate color according to Status.

You can use <Run /> to combine text with binding text.

<TextBlock Name="txtStatus"  Margin="10,2,0,0" Width="350" TextTrimming="WordEllipsis">
    <Run Text="Status :" /> <Run Text="{Binding Status}" Foreground="{Binding Status, Converter={StaticResource StatusToColor}}"/>
</TextBlock>

نصائح أخرى

You could also add a new property (StateColor) to your DataContext, wrap your textblock in a Border control and bind the background of this border to the property (simple but maybe against MVVM, because you get some UI stuff into your viewmodel).

An other way to achieve your goal is by using a StyleSelector, see: http://zamjad.wordpress.com/2010/01/01/applying-style-conditionally/ http://blogs.u2u.be/diederik/post/2012/05/22/Using-Dynamic-XAML-in-Windows-8-Metro.aspx

cheers, Alex

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top