XAML 如何在元素中更改DataContext中的路径?

bvn4nwqk  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(132)

我有一个

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

我如何改变我的Path中的索引0?也许我可以用转换器来做,但我不知道如何将它绑定到我的DataContextPath

wgmfuz8q

wgmfuz8q1#

您可以建立接受数组或清单以及索引的多值转换子。

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();
   }
}

转换器需要第一个参数实现IList接口,以便进行索引访问(数组和通用列表类型支持此操作)。第二个参数是索引。您必须在范围内的任何资源字典中创建转换器的示例,例如:

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

最后,在绑定列表和索引的MultiBinding中使用转换器。

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

相关问题