2014-07-04 27 views
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> 

如何在我的代碼中傳遞這種風格?這是做事情的好方法嗎?

+0

您需要將資源放置在代碼隱藏設置可以訪問它。例如'path.Style =(Style)App.Current.Resources [「statusIndicatorRed」];'如果資源是在App.xaml中定義的,或者在由App.Xaml引用的ResourceDictionary中定義的。 – Silvermind

+0

啊哈!我認爲這個問題可能是因爲背後的代碼無法看到這個風格被定義在哪裏。感謝您的幫助,我會進行必要的更改。 – ocajian

+0

@Silvermind最好的做法是在App.Xaml引用的單獨文件中定義我的樣式? – ocajian

回答

5

這是我做過什麼來解決這個問題:

我創建了一個名爲Styles.xaml

新的ResourceDictionary在我的App.xaml我引用的資源如下

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

在我的代碼隱藏我調用資源如下

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

+1考慮添加'Styles.xaml'的相關部分。 – Silvermind

相關問題