从转换器返回动态资源

发布于 2024-12-07 06:41:42 字数 1381 浏览 0 评论 0原文

我想根据布尔值的状态(在本例中为复选框的状态)更改 WPF 控件的颜色。 只要我使用 StaticResources:

我的控件

<TextBox Name="WarnStatusBox" TextWrapping="Wrap" Style="{DynamicResource StatusTextBox}" Width="72" Height="50" Background="{Binding ElementName=WarnStatusSource, Path=IsChecked, Converter={StaticResource BoolToWarningConverter}, ConverterParameter={RelativeSource self}}">Status</TextBox>

我的转换器:

[ValueConversion(typeof(bool), typeof(Brush))]

public class BoolToWarningConverter : IValueConverter
{
    public FrameworkElement FrameElem = new FrameworkElement();

    public object Convert(object value, Type targetType,
        object parameter, CultureInfo culture)
    {                      
        bool state = (bool)value;
        try
        {              
            if (state == true)
                return (FrameElem.TryFindResource("WarningColor") as Brush);
            else
                return (Brushes.Transparent);
        }

        catch (ResourceReferenceKeyNotFoundException)
        {
            return new SolidColorBrush(Colors.LightGray);
        }
    }

    public object ConvertBack(object value, Type targetType,
        object parameter, CultureInfo culture)
    {
        return null;
    }
}

问题是我对资源“WarningColor”有多个定义,具体取决于设置白天模式或夜间模式。这些事件不会触发警告颜色发生更改。 有没有办法使返回值动态化或者我需要重新考虑我的设计?

I want to change the color of a WPF control depending on the state of a bool, in this case the state of a checkbox.
This works fine as long as I'm working with StaticResources:

My control

<TextBox Name="WarnStatusBox" TextWrapping="Wrap" Style="{DynamicResource StatusTextBox}" Width="72" Height="50" Background="{Binding ElementName=WarnStatusSource, Path=IsChecked, Converter={StaticResource BoolToWarningConverter}, ConverterParameter={RelativeSource self}}">Status</TextBox>

My converter:

[ValueConversion(typeof(bool), typeof(Brush))]

public class BoolToWarningConverter : IValueConverter
{
    public FrameworkElement FrameElem = new FrameworkElement();

    public object Convert(object value, Type targetType,
        object parameter, CultureInfo culture)
    {                      
        bool state = (bool)value;
        try
        {              
            if (state == true)
                return (FrameElem.TryFindResource("WarningColor") as Brush);
            else
                return (Brushes.Transparent);
        }

        catch (ResourceReferenceKeyNotFoundException)
        {
            return new SolidColorBrush(Colors.LightGray);
        }
    }

    public object ConvertBack(object value, Type targetType,
        object parameter, CultureInfo culture)
    {
        return null;
    }
}

The problem is that I have several definitions of the Resource "WarningColor" dependant on setting day mode or night mode. These events does not trig the WarningColor to change.
Is there a way to make the return value dynamic or do I need to rethink my design?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

柠栀 2024-12-14 06:41:42

您无法从转换器返回动态内容,但如果您唯一的条件是布尔值,您可以使用 Triggers 轻松地将整个转换器替换为 Style

例如,

<Style TargetType="TextBox">
    <Setter Property="Background" Value="Transparent" />
    <Style.Triggers>
        <DataTrigger Binding="{Binding IsChecked, ElementName=WarnStatusSource}" Value="True">
            <Setter Property="Background" Value="{DynamicResource WarningColor}" />
        </DataTrigger>
    </Style.Triggers>
</Style>

如果现在资源具有该键已更改,背景也应更改。

You cannot return something dynamic from a converter, but if your only condition is a bool you can easily replace the whole converter with a Style using Triggers:

e.g.

<Style TargetType="TextBox">
    <Setter Property="Background" Value="Transparent" />
    <Style.Triggers>
        <DataTrigger Binding="{Binding IsChecked, ElementName=WarnStatusSource}" Value="True">
            <Setter Property="Background" Value="{DynamicResource WarningColor}" />
        </DataTrigger>
    </Style.Triggers>
</Style>

If now the resource with that key is changed the background should change as well.

皇甫轩 2024-12-14 06:41:42

返回动态资源引用的方法非常简单,使用 DynamicResourceExtension 构造函数并为其提供资源键。

用法:

return new DynamicResourceExtension(Provider.ForegroundBrush);

Provider 类的定义应包含键:

public static ResourceKey ForegroundBrush 
{ 
    get 
    { 
        return new ComponentResourceKey(typeof(Provider), "ForegroundBrush"); 
    } 
}

并且该键的值将在资源字典中声明:

<ResourceDictionary
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     xmlns:theme="clr-namespace:Settings.Appearance;assembly=AppearanceSettingsProvider">

<Color x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type theme:Provider}, ResourceId=ForegroundColor}">#FF0000FF</Color>

<SolidColorBrush x:Key="{ComponentResourceKey {x:Type theme:Provider}, ForegroundBrush}" Color="{DynamicResource {ComponentResourceKey {x:Type theme:Provider}, ForegroundColor}}" />
</ResourceDictionary>

这样,转换器将根据提供的资源键动态地将 DynamicResource 分配给绑定属性。

The way to return a dynamic resource reference is pretty simple using a DynamicResourceExtension constructor and supplying it a resource key.

Usage:

return new DynamicResourceExtension(Provider.ForegroundBrush);

Definition of the Provider class should contains the key:

public static ResourceKey ForegroundBrush 
{ 
    get 
    { 
        return new ComponentResourceKey(typeof(Provider), "ForegroundBrush"); 
    } 
}

And the value for the key would be declared in the resource dictionary:

<ResourceDictionary
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     xmlns:theme="clr-namespace:Settings.Appearance;assembly=AppearanceSettingsProvider">

<Color x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type theme:Provider}, ResourceId=ForegroundColor}">#FF0000FF</Color>

<SolidColorBrush x:Key="{ComponentResourceKey {x:Type theme:Provider}, ForegroundBrush}" Color="{DynamicResource {ComponentResourceKey {x:Type theme:Provider}, ForegroundColor}}" />
</ResourceDictionary>

This way, the converter would dynamically assign a DynamicResource to the bound property depending on the resource key supplied.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文