Home > Back-end >  NET MAUI Reference element from global style
NET MAUI Reference element from global style

Time:11-08

In my NET 7 MAUI App I have the following Style resource defined in my global styles which throws an exception because it cannot find the element "MainContentGrid". This style of course works fine if in the same xaml file as where the Grid lives but as I want to use on several screens I need to put in Styles.xaml

  <converters:IsGreaterThanConverter x:Key="IsGreaterThanConverter" />

 <Style x:Key="ResponsiveGridStyle" TargetType="Grid">
            <Style.Triggers>
                <DataTrigger TargetType="Grid" Binding="{Binding Path=Width, 
                                       Source={x:Reference MainContentGrid}, 
                                       Converter={StaticResource IsGreaterThanConverter}, 
                                       ConverterParameter=1024}"
                             Value="True">
                    <Setter TargetName="MasterColumn" Property="ColumnDefinition.Width" Value="480"/>
                     <Setter TargetName="DetailColumn" Property="ColumnDefinition.Width" Value="*"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>

Then in each separate xaml file I wish to refer to the style

<Grid x:Name="MainContentGrid"  Style="{StaticResource ResponsiveGridStyle}">
     <Grid.ColumnDefinitions>
                    <ColumnDefinition x:Name="MasterColumn" Width="*"/>
                    <ColumnDefinition x:Name="DetailColumn" Width="0" />
       </Grid.ColumnDefinitions>
</Grid>

How to do? Thanks

CodePudding user response:

You can check this doc, it talks about Style in details. It could be helpful to you.

The exception that it cannot find the element "MainContentGrid" is because MainContentGrid is not in the current file(Styles.xaml). It's not able to set a binding. You can Imitate the definition of other styles in Styles.xaml.

  • Related