(wpf) Application.Current.Resources vs FindResource

So, I am doing a GUI with WPF in C #. It looks like this:

W4f5uMz.png

This is not done right now. These 2 lines are my attempt to create some kind of data table, and they are hardcoded in XAML.

Now I implement the functionality of the add new fruit button in C #. I have the following style in XAML that defines how the background images of strings look:

<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"]; 

he adds a new line that looks like this:

if1NvZQ.png

As you can see, this is not entirely correct ... And stretching the window exacerbates the problem:

6AfTEnX.png

Looks like don't follow the Stretch style property.

But then if instead change the style loading code to

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

This works great:

NwI9aFo.png

(Again, the application is not finished, so do not worry about it), but my main question is: what is the difference between Application.Current.Resources[] and FindResource() ? Why does someone seem to ignore some properties and not others? And how, if at all possible, can my Application.Current.Resources[] work correctly?

+6
c # styles wpf
Jul 17 '13 at 16:11
source share
1 answer

Resources can be defined for almost any element in the visual tree. FrameworkElement.FindResource () will move through the tree looking for a resource in each node, and ultimately make it fully accessible to the application. Application.Current.Resources [] skips all this and goes directly to the application resources. You almost always want to use FindResource () so that you can redefine styles at different points.

+12
Jul 17 '13 at 16:38
source share



All Articles