绑定索引器

时间:2016-02-13 21:10:03

标签: xaml binding win-universal-app

我的应用中有一系列项目,我想将Content的{​​{1}}设置为其中一项。该项目将由ContentPresenter索引随机定义。我可以绑定这样的项目:

int

但不是这样的:

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

我已经看到一些建议在WPF中使用<ContentPresenter Content={Binding Items[{Binding Index}]}/> 的答案,但这在UWP中是不可用的。还有其他选择吗?

1 个答案:

答案 0 :(得分:1)

您可以创建一个视图模型属性,返回Items[Index]

public string RandomItem => Items[Index];

要使PropertyChanged通知正常工作,您需要在IndexItems更改时提升事件,例如:

public int Index
{
    get { return _index; }
    set
    {
        _index = value;
        RaisePropertyChanged();
        RaisePropertyChanged(() => RandomItem);
    }
}

如果您希望在视图中使用逻辑并采用多重绑定方式,则可以使用Cimbalino toolkit。为此,首先添加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>
相关问题