Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(wpf) Application.Current.Resources vs FindResource

Tags:

c#

styles

wpf

So, I'm making a GUI thingy with WPF in C#. It looks like this:

It's not done right now. Those 2 rows are my attempt at making a sort of data table, and they are hard-coded in the XAML.

Now, I am implementing the add new fruit button functionality in the C#. I have the following style in the XAML that governs what the background images of the rows should look like:

<Style x:Key="stretchImage" TargetType="{x:Type Image}">
    <Setter Property="VerticalAlignment" Value="Stretch"/>
    <Setter Property="HorizontalAlignment" Value="Stretch"/>
    <Setter Property="Stretch" Value="Fill"/>
</Style>

So, in the code, I create an image for each column, col0, col1, and col2, and if I use the following code,

col0.Style = (Style)Application.Current.Resources["stretchImage"];
col1.Style = (Style)Application.Current.Resources["stretchImage"];
col2.Style = (Style)Application.Current.Resources["stretchImage"];

it adds a new row that looks like this:

As you can see, it's not quite right... And stretching the window exacerbates the problem:

It seems to not be respecting the style's "Stretch" property.

But then, if I instead change my style loading code to

col0.Style = (Style)FindResource("stretchImage");
col1.Style = (Style)FindResource("stretchImage");
col2.Style = (Style)FindResource("stretchImage");

It works beautifully:

(Again, the app isn't finished, so don't worry about that), but my main question is: What's the difference between Application.Current.Resources[] and FindResource()? Why does one seem to ignore some of the properties while the other doesn't? And how, if at all possible, might I get Application.Current.Resources[] to work properly?

like image 837
Pojo Avatar asked Jul 17 '13 16:07

Pojo


1 Answers

Resources can be defined on almost any element in the visual tree. FrameworkElement.FindResource() will walk up the tree looking for the resource at each node, and eventually make it all the way to Application. Application.Current.Resources[] skips all of this and goes straight for the resources on the Application. You almost always want to use FindResource() so you can override styles at various points.

like image 149
philq Avatar answered Sep 19 '22 08:09

philq