绑定索引器
Binding Indexer
我的应用程序中有一组项目,我想将 ContentPresenter
的 Content
设置为这些项目之一。该项目将由 int
索引随机定义。我可以像这样绑定一个项目:
<ContentPresenter Content={Binding Items[0]}/>
但不是这样的:
<ContentPresenter Content={Binding Items[{Binding Index}]}/>
我看到许多建议在 WPF 中使用 MultiBinding
的答案,但这在 UWP 中不可用。有其他选择吗?
您可以创建视图模型 属性,返回 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>
我的应用程序中有一组项目,我想将 ContentPresenter
的 Content
设置为这些项目之一。该项目将由 int
索引随机定义。我可以像这样绑定一个项目:
<ContentPresenter Content={Binding Items[0]}/>
但不是这样的:
<ContentPresenter Content={Binding Items[{Binding Index}]}/>
我看到许多建议在 WPF 中使用 MultiBinding
的答案,但这在 UWP 中不可用。有其他选择吗?
您可以创建视图模型 属性,返回 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>