簡體   English   中英

如何將樣式綁定到控件

[英]How can I binding a style to Controls

我嘗試使圖像具有閃爍樣式,並且我打算動態分配此樣式,並為具有依賴性屬性HasError的某些圖像分配這種樣式,當HasErro = True時,圖像閃爍,否則不閃爍並且樣式設置為null。

這是我的樣式,可以正常工作:

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

這是我的風格綁定:

<Image x:Name="imgErro" Style="{Binding HasError, Converter={StaticResource ErrorBooleanAnimate}, ElementName=userControl}"/>

這是我的價值轉換器,有兩種解決方案,但不起作用:

    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();
    }
}

解決此問題的最佳解決方案是什么?

您需要在“應用程序資源”下定義資源以使代碼正常工作。

仍然,如果要在UserControl資源下定義它,則需要將userControl實例傳遞給轉換器並在其資源中進行搜索。

(Style)userControl.TryFindResource("myImageAnimateStyle");

您可以將樣式傳遞給轉換器:

<Image Style="{Binding HasError,
                       Converter={StaticResource ErrorBooleanAnimate},
                       ConverterParameter={StaticResource myImageAnimateStyle},
                       RelativeSource={RelativeSource Self}}"/>

只需在轉換器中返回parameter

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM