在C#代码后面传递XAML中定义的静态资源样式

时间:2014-07-04 09:38:51

标签: c# xaml

我正在构建一个WPF应用程序。 XAML用于前端,C#用于后面的代码

我有以下代码段为我动态生成我的XAML。

if (station_item.Checker_Setup.First().Checker_Log.OrderByDescending(log => log.date).First().Status.status_key == 2)
                    {
                        Path path = new Path();
                        path.Data = new RectangleGeometry(new Rect(0, 0, 19, 21), 3, 3);
                        path.Style = "{StaticResource statusIndicatorRed}";
                        TextBlock block = new TextBlock();
                        block.Text = station_item.station_name;
                        WrapBox.Children.Add(path);
                        WrapBox.Children.Add(block);
                    } 

然而我在哪里

path.Style = "{StaticResource statusIndicatorRed}";

我收到以下错误

无法将类型String隐式转换为System.Windows.Style

该样式在我的MainWindow.xaml中定义如下

<Style x:Key="statusIndicatorRed" TargetType="Path">
        <Setter Property="Fill" Value="#B2203D" />
        <Setter Property="Width" Value="19px" />
        <Setter Property="HorizontalAlignment" Value="Left" />
        <Setter Property="ToolTipService.ShowDuration" Value="30000" />
        <Setter Property="Cursor" Value="Help" />
</Style>

如何在我的代码中传递此样式?这甚至是做事的好方法吗?

1 个答案:

答案 0 :(得分:5)

这就是我为解决这个问题所做的工作:

我创建了一个名为Styles.xaml的新ResourceDictionary

在我的App.xaml中,我引用了以下资源

<Application.Resources>
    <ResourceDictionary Source="Styles.xaml" />
</Application.Resources>

在我的代码隐藏中,我将资源调用如下

path.Style = (Style)App.Current.Resources["statusIndicatorRed"];