Home > Software design >  Is it possible to DataBind an integer resource in maui xaml?
Is it possible to DataBind an integer resource in maui xaml?

Time:12-29

I'm trying to bind the width of a button datatemplate to a property in my viewmodel but it doesn't seem like I can do that because the itemssource of my collectionview defines the source of my button as one object of the collection, but the property I'd like to bind to is a property of the object containing that collection. `

            <CollectionView ItemsSource="{Binding Table}" HorizontalOptions="CenterAndExpand">
                <CollectionView.Resources>
                </CollectionView.Resources>
                <CollectionView.ItemsLayout>
                    <GridItemsLayout Orientation="Horizontal" Span="{Binding Span}" HorizontalItemSpacing="2" VerticalItemSpacing="2"/>
                </CollectionView.ItemsLayout>
                <CollectionView.ItemTemplate>
                    <DataTemplate>
                        <Button Text="{Binding Adjacent}" Command="{Binding TileChangedCommand}" CommandParameter="{Binding}" IsEnabled="{Binding IsEnabled}" BackgroundColor="Grey" HeightRequest="{Binding TableHeight}" WidthRequest="{Binding TableWidth}" CornerRadius="0" Padding="0"/>
                    </DataTemplate>
                </CollectionView.ItemTemplate>
            </CollectionView>

`

I came up with the idea to just create an int resource in my collectionview and bind that to the desired property because my collectionview is already bound to the appropriate object for my binding. The problem is that doesn't seem possible, because when I try to do this:

                <CollectionView.Resources>
                    <x:Int32 x:Key="width">
                        <Binding Path="TableWidth"/>
                    </x:Int32>
                </CollectionView.Resources>

I get the error: "The type 'Int32' does not support direct content." Is there any way this would be possible?

CodePudding user response:

You can try to use the binding to an ancestor to bind the button's width to the viewmodel's property. Such as:

In the xaml:

xmlns:local="clr-namespace:YourProjectName"
...
<CollectionView.ItemTemplate>
      <DataTemplate>
           <Button ...
WidthRequest="{Binding Source={RelativeSource AncestorType={x:Type local:YourViewModel}}, Path=TableWidth}" 
.../>
      </DataTemplate>
</CollectionView.ItemTemplate>
  • Related