簡體   English   中英

Windows Phone 8中顏色的條件StaticResource

[英]Conditional StaticResource for color in Windows Phone 8

在WP8中,我想根據我綁定中的布爾屬性將TextBlock的前景色設置為其他顏色。 此外,我還想為顏色使用StaticResource。

我研究過的一種可能性是為此使用ValueConverter,但到目前為止無法與StaticResources一起使用。 我嘗試的代碼是這樣的:

<TextBlock Foreground="{Binding IsBlue, Converter={StaticResource BoolToColorConverter}}" />

和我的轉換器(我不認為返回字符串會起作用,但還是決定對其進行測試):

public class BoolToColorConverter : IValueConverter{
  public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
        return (value is bool && (bool)value) ? "{StaticResource PhoneAccentBrush}" : "{StaticResource PhoneSubtleBrush}";
        }
}

此外,我研究了使用DataTriggers,但發現WP8沒有直接支持。

我還沒有嘗試過依賴屬性,因為我想先確保我沒有錯過一種更簡單,更明顯的方法來解決此問題。

最好的創建方式是什么?

您有兩種方法可以解決此問題:

您可以通過附加屬性擴展轉換器,該附加屬性將由綁定填充

public class BooleanToBrushConverter
        : IValueConverter
    {
        public Brush TrueBrush { get; set; }
        public Brush FalseBrush { get; set; }

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value is bool)
            {
                return (bool) value
                    ? TrueBrush
                    : FalseBrush;
            }

            return value;
        }

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

現在您可以通過頁面資源對其進行初始化

<BooleanToBrushConverter x:Key="BooleanToBrushConverter" TrueBrush="{StaticResource PhoneAccentBrush}" FalseColor="{StaticResource PhoneSubtleBrush}" />

並盡可能簡單地使用它

<TextBlock Foreground="{Binding IsBlue, Converter={StaticResource BooleanToBrushConverter}}" />

第二種解決方案是修復代碼以從應用程序資源中恢復畫筆

public class BoolToColorConverter
  : IValueConverter{
  public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {

        return (value is bool && (bool)value) ? Application.Current.Resources["PhoneAccentBrush"] : Application.Current.Resources["PhoneSubtleBrush"];
        }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM