我有一個支持多種配色方案的WPF應用程序(我通過在運行時交換Black.Xaml和White.XAML文件來實現此目的,其中兩個都使用同一個關鍵點,然後使用DynamicResources訪問它們)。WPF主題和轉換器
現在我必須表明紅的值低於0和綠色以上0值。 (我爲每個主題都有不同的綠色和紅色)。所以,我的轉換是這樣的
XAML
<Converters:PositiveNegativeConverter x:Key="PositiveNegativeConverter" DownColor="{DynamicResource RedPrimaryBrush}" UpColor="{DynamicResource GreenPrimaryBrush}" NormalColor="{DynamicResource BluePrimaryBrush}"/>
轉換
public class PositiveNegativeConverter : DependencyObject, IValueConverter
{
#region DependencyProperty
public SolidColorBrush UpColor
{
get { return (SolidColorBrush)GetValue(UpColorProperty); }
set { SetValue(UpColorProperty, value); }
}
// Using a DependencyProperty as the backing store for UpColor. This enables animation, styling, binding, etc...
public static readonly DependencyProperty UpColorProperty =
DependencyProperty.Register("UpColor", typeof(SolidColorBrush), typeof(PositiveNegativeConverter), new PropertyMetadata(null));
public SolidColorBrush DownColor
{
get { return (SolidColorBrush)GetValue(DownColorProperty); }
set { SetValue(DownColorProperty, value); }
}
// Using a DependencyProperty as the backing store for DownColor. This enables animation, styling, binding, etc...
public static readonly DependencyProperty DownColorProperty =
DependencyProperty.Register("DownColor", typeof(SolidColorBrush), typeof(PositiveNegativeConverter), new PropertyMetadata(null));
public SolidColorBrush NormalColor
{
get { return (SolidColorBrush)GetValue(NormalColorProperty); }
set { SetValue(NormalColorProperty, value); }
}
// Using a DependencyProperty as the backing store for NormalColor. This enables animation, styling, binding, etc...
public static readonly DependencyProperty NormalColorProperty =
DependencyProperty.Register("NormalColor", typeof(SolidColorBrush), typeof(PositiveNegativeConverter), new PropertyMetadata(null));
#endregion
#region IValueConverter
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is double)
{
double dblValue = (double)value;
if (dblValue > 0)
{
return UpColor;
}
else if (dblValue < 0)
{
return DownColor;
}
}
return NormalColor;
}
}
但是當我改變在運行時的主題,我沒有得到被打到的轉換器,甚至我的畫筆在轉換器中的屬性會發生變化(例如:白色特定綠色沒有變成黑色特定綠色),那麼我怎樣才能達到可接受的結果。
沒有轉換器的所有其他場景運行良好。
您可以提供一個專用的類'ThemeManager',當您更改當前主題時,您可以讓事件發生。然後,視圖可以訂閱它(訂閱可以移動到附加的行爲,如果你喜歡MVVM的概念)和更新綁定('PropertyChanged(「」)'或重新分配'DataContext')。沒有其他辦法,你必須觸發「PropertyChanged」事件或自己處理綁定。轉換器僅在此之後被調用。 – Sinatr