Xaml 绑定索引器

Xaml 绑定索引器,xaml,binding,win-universal-app,Xaml,Binding,Win Universal App,我的应用程序中有一组项目,我想将ContentPresenter的Content设置为这些项目之一。该项将由int索引随机定义。我可以像这样绑定一个项目: <ContentPresenter Content={Binding Items[0]}/> <ContentPresenter Content={Binding Items[{Binding Index}]}/> 但不是这样: <ContentPresenter Content={Binding Ite

我的应用程序中有一组项目,我想将
ContentPresenter
Content
设置为这些项目之一。该项将由
int
索引随机定义。我可以像这样绑定一个项目:

<ContentPresenter Content={Binding Items[0]}/>
<ContentPresenter Content={Binding Items[{Binding Index}]}/>

但不是这样:

<ContentPresenter Content={Binding Items[0]}/>
<ContentPresenter Content={Binding Items[{Binding Index}]}/>


我看到很多答案建议在WPF中使用
MultiBinding
,但这在UWP中不可用。有其他选择吗?

您可以创建视图模型属性,返回
项[索引]

public string RandomItem => Items[Index];
要使
属性更改
通知生效,您需要在
索引
项目
更改时引发事件,例如:

public int Index
{
    get { return _index; }
    set
    {
        _index = value;
        RaisePropertyChanged();
        RaisePropertyChanged(() => RandomItem);
    }
}
如果您希望在视图中使用逻辑并采用多重绑定方式,则可以使用。为此,首先添加2个NuGet包:

现在,您可以创建一个转换器:

public class CollectionIndexConverter : MultiValueConverterBase
{
    public override object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        var collection = (IList) values[0];
        var index = (int?) values[1];
        return index.HasValue ? collection[index.Value] : null;
    }

    public override object[] ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new System.NotImplementedException();
    }
}
并从XAML中使用它:

<ContentPresenter>
    <interactivity:Interaction.Behaviors>
        <behaviors:MultiBindingBehavior PropertyName="Content" Converter="{StaticResource CollectionIndexConverter}">
            <behaviors:MultiBindingItem Value="{Binding Items}" />
            <behaviors:MultiBindingItem Value="{Binding Index}" />
        </behaviors:MultiBindingBehavior>
    </interactivity:Interaction.Behaviors>
</ContentPresenter>