【问题标题】:IValueConverter to convert a resource referenced by StaticResourceIValueConverter 转换 StaticResource 引用的资源
【发布时间】:2016-06-02 21:41:16
【问题描述】:

我希望使用 IValueConverter 和我从应用程序的资源中获得的值。我注意到几年前有人在这里问过类似的问题:How to bind to a StaticResource with a Converter?

但是,将 Source 属性更新为资源中的对象对我不起作用。我的特殊情况:

<TextBlock Text="SampleText" Foreground="{Binding Source={StaticResource AppThemeColor}, Converter={StaticResource ThemeColorToBrushConverter}, ConverterParameter={StaticResource ApplicationForegroundThemeBrush}, Mode=OneWay}" />

AppThemeColor 是在应用启动的早期阶段在后面的代码中动态定义和设置的。转换器中的逻辑只是说使用提供的颜色,除非应用程序处于高对比度模式,在这种情况下,它使用 ConverterParameter 中提供的画笔。

有谁知道我在这里可能遇到的任何陷阱?没有编译或运行时错误。文本没有出现,转换器的转换似乎没有被调用。

编辑:有些人问我如何动态设置 AppThemeColor。我只是在 App.xaml.cs 的 OnActivatedAsync 中添加了以下单行代码:

Application.Current.Resources[AppThemeColorResourceKey] = (themeExists) ? branding.ThemeColor : blueThemeColor;

【问题讨论】:

  • 告诉我们您在代码中设置AppThemeColor 的位置?
  • 如果是动态设置的,有没有试过用DynamicResource代替StaticResource?
  • DynamicResource 不是我在 UWP 应用程序中的一个选项(也许应该在一开始就澄清这一点),尽管这确实不应该是问题。我将使用设置 AppThemeColor 的单行代码更新我提出的问题。

标签: wpf xaml staticresource


【解决方案1】:

您可以将这些 StaticResources 转换为您的应用的“样式”class,并将其分配给Window.DataContext

我认为这将是您案件的最佳方法。

如果您的项目使用 MVVM 模式,请使用 singleton 模式创建该类,并将其用作需要该样式的 ViewModel 的属性。

风格类别:

using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Media;

public class DefaultStyleClass : INotifyPropertyChanged
{
    private Brush _appThemeColor;
    public Brush AppThemeColor
    {
        get { return _appThemeColor; }
        set
        {
            if(value != _appThemeColor)
            {
                _appThemeColor = value;
                NotifyPropertyChanged();
            }
        }
    }

    public DefaultStyleClass()
    {
        AppThemeColor = Brushes.Red;
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
    {
        var propertyChanged = PropertyChanged;
        if (propertyChanged != null)
        {
            propertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}


现在您需要将其分配给Window

DataContext

代码:

public DefaultStyleClass StyleContext;
public MainWindow()
{
    InitializeComponent();

    StyleContext = new DefaultStyleClass();
    DataContext = StyleContext;
}


在 XAML 上:

<TextBlock Text="SampleText",
           Foreground="{Binding AppThemeColor},
           Converter={StaticResource ThemeColorToBrushConverter},
           ConverterParameter={StaticResource ApplicationForegroundThemeBrush},
           Mode=OneWay}" />

【讨论】:

    猜你喜欢
    • 2015-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-24
    相关资源
    最近更新 更多