1

I am building a WPF application. XAML used for front end and C# for code behind

I have the following section of code that generates my XAML for me dynamically.

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); } 

However where I have

path.Style = "{StaticResource statusIndicatorRed}"; 

I get the following error

Cannot implicitly convert type String to System.Windows.Style

The style is defined in my MainWindow.xaml as follows

<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> 

How would I pass this style through in my code behind? Is this even a good way to do things?

4
  • You would need to place the resource where your code-behind set up has access to it. For example path.Style = (Style)App.Current.Resources["statusIndicatorRed"]; if the resource is defined in App.xaml or in a ResourceDictionary referenced by App.Xaml. Commented Jul 4, 2014 at 9:53
  • Aha! I thought the issue could be that the code behind had no way of seeing where this style was defined. Thanks for the help I shall make the changes needed then. Commented Jul 4, 2014 at 9:56
  • @Silvermind would best practice be to define my style in a seperate file referenced by App.Xaml? Commented Jul 4, 2014 at 9:58
  • Yes, using seperate ResourceDictionaries to group styles is a good idea. Commented Jul 4, 2014 at 10:10

1 Answer 1

6

This is what I did to fix the issue:

I created a new ResourceDictionary named Styles.xaml

In my App.xaml I referenced the resource as follows

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

In my codebehind I called the resource as follows

path.Style = (Style)App.Current.Resources["statusIndicatorRed"]; 
Sign up to request clarification or add additional context in comments.

1 Comment

+1 Consider adding the relevant part of Styles.xaml.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.