Dynamic grid columns and access to StaticResources
In my grid I have a static columns, and when I click to a button I add some dynamic columns :
class ItemConstraintColumn : DataGridTemplateColumn
{
public ItemConstraintColumn(ReportEventItemConstraint _ic)
{
StringBuilder sb = new StringBuilder();
sb.Append("<DataTemplate ");
sb.Append("xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' ");
sb.Append("xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' ");
sb.Append("xmlns:local='clr-namespace:MyNameSpace;assembly=MyAssembly'> ");
sb.Append("<local:SignalControl DataContext=\"{Binding Source={StaticResource SignalControlVM}}\" />");
sb.Append("</DataTemplate>");
CellTemplate = (DataTemplate)XamlReader.Load(sb.ToString());
Header = _ic.Name;开发者_如何学编程
}
}
The problem is I can't access to the StaticResource declared in my Xaml page, so I can't bind my control ... Can you please tell me what's wrong with that ? Thanks
On the code behind you can use the below code to find the static resource declared in xaml
this.FindResource("ResourceName"))
It looks like you are creating your DataContext as a completely self-contained Xaml file.
The bindings are evaluated at load time, at which time your snippet is not part of the visual tree, so nothing is found (there is no parent page, and therefore no resource, at the time it is parsed).
You are better off loading it as you are, find the local:SignalControl element within it, and bind the DataContext using code instead.
While useless by itself, Shebin's suggestion on locating a resource will do the last part of the job. i.e. finding the resource to bind to.
精彩评论