Home > Net >  How to change a Path in DataContext in Element?
How to change a Path in DataContext in Element?

Time:07-27

I have a

<Grid DataContext="{Binding Path=ListOFFighters[0],
                            Mode=TwoWay,
                            UpdateSourceTrigger=PropertyChanged}">
</Grid>

How can I change the index 0 in my Path? Perhaps I can do it with converter, but I have no idea how bind it to my DataContext Path.

CodePudding user response:

You can create a multi-value converter that takes an array or list as well as an index.

public class IndexedBindingConverter : IMultiValueConverter
{
   public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
   {
      return values.Length < 2 || !(values[0] is IList list) || !(values[1] is int index) ? Binding.DoNothing : list[index];
   }

   public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
   {
      throw new InvalidOperationException();
   }
}

The converter expects the first parameter to implement the IList interface in order to have indexed access (arrays and common list types support this). The second parameter is the index. You have to create an instance of the converter in any resource dictionary in scope, e.g.:

<Window.Resources>
   <local:IndexedBindingConverter x:Key="IndexedBindingConverter"/>
</Window.Resources>

Finally, use the converter in a MultiBinding that binds the list and index.

<Grid>
   <Grid.DataContext>
      <MultiBinding Converter="{StaticResource IndexedBindingConverter}">
         <Binding Path="ListOFFighters"/>
         <Binding Path="YourIndex"/>
      </MultiBinding>
   </Grid.DataContext>
   <!-- ...your markup. -->
</Grid>
  • Related