您可以創建一個視圖模型屬性,返回Items[Index]
:
public string RandomItem => Items[Index];
爲PropertyChanged
通知工作,你將需要提高的情況下,只要Index
或Items
的變化,例如:
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>