Search code examples
uno-platform

How to bind without RelativeSource FindAncestor?


I need some binding help on my Uno UWP Project. I have the following objects:

    public class ViewModel : INotifyPropertyChanged
    {
        public ObservableCollection<Picture> Pictures {get;set;}
        public int ImageWidth {get;set;}
    }
    public class Picture : INotifyPropertyChanged
    {
        public string URL {get;set;}
        public int ImageWidth {get;set;}
    }

I have the following view:

<Page>
    <Grid>
        <Grid.RowDefinition>
            <RowDefinition Height=*/>
            <RowDefinition Height="Auto"/>
        </Grid.Rowdefinition>   
        <GridView ItemsSource="{Binding Pictures}" SelectionMode="Extended" IsMultiSelectCheckBoxEnabled="False"
                  VerticalAlignment="Stretch" HorizontalAlignment="Stretch" SelectionChanged="ImageSelectionChanged" >
            <GridView.ItemContainerStyle>
                <Style TargetType="GridViewItem">
                    <Setter Property="Margin" Value="10"/>
                </Style>
            </GridView.ItemContainerStyle>
            <GridView.ItemsPanel>
                <ItemsPanelTemplate>
                    <ItemsWrapGrid MaximumRowsOrColumns="5" Orientation="Horizontal"/>
                </ItemsPanelTemplate>
            </GridView.ItemsPanel>
            <GridView.ItemTemplate>
                <DataTemplate>
                    <Grid Margin="4">
                        <Image Source="{Binding URL}" Width="{Binding ImageWidth,Mode=TwoWay}" MinWidth="200"/>
                    </Grid>
                </DataTemplate>
            </GridView.ItemTemplate>
        </GridView>
       <Slider Grid.Row="1" Width="200" Minimum="200" Maximum="1500" StepFrequency="100" TickPlacement="Outside" VerticalAlignment="Bottom" Margin="20,0"
                       Value="{Binding ImageWidth, Mode=TwoWay}" />
    </Grid>
</Page> 

The Page DataContext is ViewModel. This works, because the Picture class has an ImageWidth. Instead, I would like to bind to the ViewModel.ImageWidth property. How can I do this in Uno?


Solution

  • Assuming you want your Slider to change the width of all pictures,

    you can share the ImageWidth by changing your entities like this:

        public class ViewModel : INotifyPropertyChanged
        {
            public ObservableCollection<Picture> Pictures {get;set;}
            public int ImageWidth {get;set;}
        }
        public class Picture : INotifyPropertyChanged
        {
            public ViewModel Parent {get;}
            public string URL {get;set;}
        }
    

    and then use the following binding in the item template:

    <Image Source="{Binding URL}"
           Width="{Binding Parent.ImageWidth}"
           MinWidth="200"/>