1

I am using Xamarin forms.

I have a simple View that contains a couple of list views. The whole view has a BindingContext with a viewmodel. The view model class contains a BackgroundColor. Question: How can I access the BackgroundColor property from within the listview's dataTemplate.

ViewModel.cs

public class TestViewModel {
 public System.Drawing.Color BackgroundColor { get; set; }
 public List<Employee> Employees { get; set; }
}

An instance of the above class is set a BindingContext to the view View.xaml

<ContextPage.... >
....
 <listview  ItemsSource="{Binding Employees}"...
  <DataTemplate>
    <Grid BackgroundColor="{Binding BackgroundColor}">

</ContentPage>

The above grid's background does not work as the current context is now on the Employee collection. So how can I access the "BackgroundColor" within the view model when in the list view.

Cheesebaron
  • 24,131
  • 15
  • 66
  • 118
Peter
  • 11
  • 1

1 Answers1

0

BackgroundColor of Grid control in Xamarin has Xamarin.Forms.Color type, but not System.Drawing.Color, so you must change type in your class.

public class TestViewModel {
 public Xamarin.Forms.Color BackgroundColor { get; set; }
 public List<Employee> Employees { get; set; }
}

UPDATE:

You can use RelativeSource FindAncestor to get desired property from TestViewModel instance.

Here, for example: https://stackoverflow.com/a/63713316/1979354

Spawn
  • 935
  • 1
  • 13
  • 32
  • 1
    Agree, but how do I map that property when I am within the list view datatemplate? .... = this does not work unless I have a property within the Employee class itself which stores background color – Peter Aug 16 '21 at 10:58
  • @Peter, i have updated answer, you need relative source to get value from parent context, when you in template. – Spawn Aug 16 '21 at 13:54
  • I had to tweak couple of things from there, may be you can add this to your answer {Binding BackgroundColor, Source={RelativeSource AncestorType={x:Type ContentPage}, Mode=FindAncestor}} It should be Source={RelativeSource.. in Xamarin RelativeSource={RelativeSource AncestorType = does not work and complaints RelativeSource is not in the BindingExtension Thanks mate, for getting that link. – Peter Aug 17 '21 at 10:21