Search code examples
c#wpfvisualbrush

Is it possible to create VisualBrush from String?


I think my question is selfexplanatory but to elaborate a little bit here is the case.

I want to assign value to Brush property at runtime. I am assigning it VisualBrush whose key I get from db by

Application.Current.FindResource("Key_Passed_from_DB");

However I have been asked to populate it from string in case that key is not available in application

for e.g. from db i will be passed

<Grid><Path Data="M404....">........</Grid>

Can this be converted to VisualBrush and assigned to my Brush property?


Solution

  • You can Parse Xaml strings into elements as long as you have the required namespaces (or add them before parsing).

    Then you can apply your parsed WPF element to a VisualBrush

    Working Example:

    string elementString = "<Grid xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" >  <Button /> </Grid>";
    
    Visual result = XamlReader.Parse(elementString) as Visual;
    
    VisualBrush myBrush = new VisualBrush(result);