gpt4 book ai didi

c# - 在 C# 代码隐藏中传递 XAML 中定义的 StaticResource 样式

转载 作者:太空宇宙 更新时间:2023-11-03 20:04:34 24 4
gpt4 key购买 nike

我正在构建一个 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>

我如何在我的代码中传递这种风格?这甚至是做事的好方法吗?

最佳答案

这是我为解决问题所做的:

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

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

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

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

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

关于c# - 在 C# 代码隐藏中传递 XAML 中定义的 StaticResource 样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24571220/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com