10

bool の状態、この場合はチェックボックスの状態に応じて、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」の定義がいくつかあることです。これらのイベントは、WarningColor の変更をトリガーしません。戻り値を動的にする方法はありますか、それとも設計を再考する必要がありますか?

4

2 に答える 2

3

コンバーターから動的なものを返すことはできませんが、唯一の条件がブール値である場合は、コンバーター全体を次Styleを使用して簡単に置き換えることができTriggersます。

例えば

<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>

そのキーを持つリソースが変更された場合、背景も変更されるはずです。

于 2011-09-30T13:35:57.850 に答える
1

動的リソース参照を返す方法は、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 をバインドされたプロパティに動的に割り当てます。

于 2013-11-07T15:24:21.933 に答える