[英]How can I binding a style to Controls
I try to make blinking style fro Image, and I intend to assign this style dynamically and assign this style for some image that has dependency property HasError, when HasErro=True the image blinking otherwise not blinking and style set to null. 我尝试使图像具有闪烁样式,并且我打算动态分配此样式,并为具有依赖性属性HasError的某些图像分配这种样式,当HasErro = True时,图像闪烁,否则不闪烁并且样式设置为null。
here is my style that works correctly: 这是我的样式,可以正常工作:
<Style x:Key="myImageAnimateStyle">
<Style.Triggers>
<EventTrigger RoutedEvent="FrameworkElement.Loaded">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetProperty="(UIElement.Opacity)"
BeginTime="0:0:0" Duration="0:0:0.5"
From="1.0" To="0.0" RepeatBehavior="Forever" AutoReverse="True"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Style.Triggers>
</Style>
and this is my style binding: 这是我的风格绑定:
<Image x:Name="imgErro" Style="{Binding HasError, Converter={StaticResource ErrorBooleanAnimate}, ElementName=userControl}"/>
and this is my Value converter with two solution but doesn't work: 这是我的价值转换器,有两种解决方案,但不起作用:
public class ErrorBooleanAnimate : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!(value is bool?))
return null;
if ((bool)value == true)
{
// Solution 1
//return "{DynamicResource myImageAnimateStyle}";
// Solution 2
Style newStyle = (Style)Application.Current.TryFindResource("myImageAnimateStyle");
return newStyle;
}
else
{
return null;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
what is the best solution for this issue? 解决此问题的最佳解决方案是什么?
You need to define resource under App resources to make your code work. 您需要在“应用程序资源”下定义资源以使代码正常工作。
Still if you want to define it under UserControl resources, you need to pass userControl instance to converter and search in it's resources. 仍然,如果要在UserControl资源下定义它,则需要将userControl实例传递给转换器并在其资源中进行搜索。
(Style)userControl.TryFindResource("myImageAnimateStyle");
You can pass the style to the converter: 您可以将样式传递给转换器:
<Image Style="{Binding HasError,
Converter={StaticResource ErrorBooleanAnimate},
ConverterParameter={StaticResource myImageAnimateStyle},
RelativeSource={RelativeSource Self}}"/>
Just return parameter
in the converter. 只需在转换器中返回
parameter
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.