1
我正在構建WPF應用程序。 XAML用於前端,C#用於代碼後面傳遞在C#中XAML中定義的StaticResource樣式代碼隱藏
我有以下代碼段,它爲我動態生成我的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>
如何在我的代碼中傳遞這種風格?這是做事情的好方法嗎?
您需要將資源放置在代碼隱藏設置可以訪問它。例如'path.Style =(Style)App.Current.Resources [「statusIndicatorRed」];'如果資源是在App.xaml中定義的,或者在由App.Xaml引用的ResourceDictionary中定義的。 – Silvermind
啊哈!我認爲這個問題可能是因爲背後的代碼無法看到這個風格被定義在哪裏。感謝您的幫助,我會進行必要的更改。 – ocajian
@Silvermind最好的做法是在App.Xaml引用的單獨文件中定義我的樣式? – ocajian