Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 77050

Changing the bindingContext of a converter parameter within a Listview

$
0
0

What i'm trying to do is Change the background color of a CollectionView (preview xf 4.0) element based on a selected value. element can be selected or running.

<CollectionView Grid.ColumnSpan="3" Grid.RowSpan="2" ItemsSource ="{Binding Projects}" SelectionMode="Single" 
            SelectedItem="{Binding SelectedProject, Mode=TwoWay}"
            SelectionChangedCommand="{Binding SelectActiveProjectCommand}"   >
    <CollectionView.ItemsLayout>
        <GridItemsLayout Orientation="Vertical" Span="3" />
    </CollectionView.ItemsLayout>

    <CollectionView.ItemTemplate>
        <DataTemplate>
            <Frame Padding="10" BackgroundColor="{StaticResource Background}" HasShadow="False" CornerRadius="0" >
                <Grid  Padding="5" BackgroundColor="{Binding Id, Converter={StaticResource BackgroundConverter}, ConverterParameter= {Binding Source={x:Reference RootPage}, Path=BindingContext}}" >
                   <!-- removded for brevity -->
                </Grid>
            </Frame>
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

When you take a look at the Grid background color, you see that i bind to the models ID property, but that the convertereParamer is bound to the RootPage and not the page's bindingcontext, which is my first code smell, for some reason i have to do it this way then extract the property i want within the converter and can't just bind to it. I have a feeling that i'm doing something wrong.

public class HighlightProjectConverter : IValueConverter
{
    static Color contrastColor = (Color)Application.Current.Resources["ContrastColor"]   ;
    static Color backgroundContrastColor = (Color)Application.Current.Resources["BackgroundContrast"];
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var ProjectID = Guid.Parse(value.ToString());

        var a = ((Binding)parameter).Source as MainPage;
        var bc = a.BindingContext as MainPageViewModel;

        return bc.ActiveTask?.ProjectId == ProjectID ? contrastColor : backgroundContrastColor;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

So, i'd really like to know if i'm doing something wrong here or if there's a better way that i'm missing, it seems silly to me that i Can't just bind to the BindingContext of the page or even teh ActiveTask property.


Viewing all articles
Browse latest Browse all 77050

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>