Binding on the View - how to get the details of parent property from a child list

Viewed 219

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.

1 Answers

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

Related