Jun 30, 2009 at 11:09 AM
Edited Jun 30, 2009 at 11:10 AM


I;m trying to set a style from code behind
These don't work:
dataGrid1.Columns[0].CellStyle = ((Style)FindResource("{StaticResource myCellStyle}"));
dataGrid1.Columns[0].CellStyle = ((Style)FindResource("myCellStyle"));
can it be done?


Jun 30, 2009 at 9:50 PM

Hi zaurska,

Yes, it looks like you are doing this correctly.  We would recommend the following:

dataGrid1.Columns[0].CellStyle = ((Style)FindResource("myCellStyle"));

As long as the Style you're trying to find is a StaticResource defined in the Resources of your Window, then this should work.


Jun 30, 2009 at 11:31 PM
thanks Samantha,
knowing that was correct has helped me see the real issue:
I should have had:
TargetType="{x:Type my:DataGridCell}">
Nov 18, 2009 at 9:38 AM

Thank you so much! I met this issue, and it has been solved with the help of your discussion.
I am continue thinking about this issue, why I can not implement it in code directly without the resource? Do you have any advice?

Nov 18, 2009 at 10:17 AM

Hi Jospeh

I am not sure I understand your question fully.

If you mean: why do you have to create a xaml resource to apply a style to a cell?

... that bothered me too, while I'm coming from Win Forms where you can access anything at design or runtime, Xaml initially felt like a step backwards and counter intuitive.

I too wanted to write something in c# like:

Style x = new Style();

x.Background= Brushes.Red

I think its because the Xaml elements have to be registered before runtime, you can then manipulate them, share them and swap them round during runtime, but they must be there to compile the Xaml, which is necessarily "Fixed" when you F5.  does that make sense?

I guess as a transition/translation between two quite different architectures there has to be some compromise, and the beauty of Xaml - as I'm finally beginning to see - is that its small, neat, efficient and static and transferable.

I'm a home/hobby developer, so all the above might be wrong! But, I am starting to get really exciting results with c#/xaml mix, and what seems weird to begin with eventually does make a lot of sense, and actually helps the structure and discipline of your code.