我正在构建一个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);
}
Run Code Online (Sandbox Code Playgroud)
但是我有
path.Style = "{StaticResource statusIndicatorRed}";
Run Code Online (Sandbox Code Playgroud)
我收到以下错误
无法将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>
Run Code Online (Sandbox Code Playgroud)
我如何在我的代码背后传递这种风格?这甚至是做事的好方法吗?
这就是我为解决这个问题所做的工作:
我创建了一个名为Styles.xaml的新ResourceDictionary
在我的App.xaml中,我引用了如下资源
<Application.Resources>
<ResourceDictionary Source="Styles.xaml" />
</Application.Resources>
Run Code Online (Sandbox Code Playgroud)
在我的代码隐藏中,我调用了如下资源
path.Style = (Style)App.Current.Resources["statusIndicatorRed"];
Run Code Online (Sandbox Code Playgroud)