lew*_*ewi 6 wpf ivalueconverter dynamicresource
我想根据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>
Run Code Online (Sandbox Code Playgroud)
我的转换器:
[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;
}
}
Run Code Online (Sandbox Code Playgroud)
问题是我有几个资源"WarningColor"的定义依赖于设置日模式或夜间模式.这些事件不会触发要更改的WarningColor.有没有办法让返回值动态或我需要重新考虑我的设计?
您无法从转换器返回动态内容,但如果您唯一的条件是 bool,您可以轻松地用以下命令替换整个转换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>
Run Code Online (Sandbox Code Playgroud)
如果现在更改了具有该键的资源,则背景也应该更改。