wpf - WPF 绑定到以哈希键为索引的可观察集合
问题描述
以下代码:
<UserControl x:Class="MyProgram.Views.MyControlContainer"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:MyProgram.Views"
xmlns:common_model="clr-namespace:MyProgram.Models;assembly=CommonTitan"
mc:Ignorable="d"
>
<Grid Background="White">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<local:MyControl x:Name="MyControl1" DataContext="{Binding MyControlCollection[8]}" Grid.Row="0" Grid.Column="0"/>
<local:MyControl x:Name="MyControl2" DataContext="{Binding MyControlCollection[9]}" Grid.Row="0" Grid.Column="1"/>
<local:MyControl x:Name="MyControl3" DataContext="{Binding MyControlCollection[10]}" Grid.Row="0" Grid.Column="2"/>
</Grid>
</UserControl>
适当地(据我所知)将我绑定到我在集合中指定的项目。在实际使用中,它将使用一个可观察的字典,这些索引是我无法提交代码的哈希值。是否可以将 2 个已知参数传递给某种转换器以获取哈希?或者甚至将 2 个值传递给转换器,最终将项目从可观察字典中返回?
解决方案
您可以传递 2 个已知值作为转换器参数,例如:
<local:MyControl x:Name="MyControl1" DataContext="{Binding MyControlCollection, Converter={StaticResource CollectionConverter}, ConverterParameters='8.9'}" />
在您的转换器类中,您可以在此处使用它,将参数解析为字符串:
public class CollectionConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (parameter != null)
{
string[] param = (parameter as string).split('.');
if (int.Parse(param[0]) == 8)
return (value as ObservableCollection)[8];
else
return (value as ObservableCollection)[0];
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new InvalidOperationException("cannot cast the value");
}
}
推荐阅读
- python - Python Tornado Swagger:每个套接字地址仅使用一次
- c - 从函数到函数的指针转移
- python - AttributeError:“模块”对象没有属性“主”
- react-native - react-navigation-drawer 与 @react-navigation/drawer 有什么区别
- docker - 使用 docker-gen 和letsencrypt-companion的docker端口映射
- spring - 具有 Office 365 身份验证的 Spring Boot 应用程序
- c# - 反序列化 JSON 时出现 ArgumentNullException
- python - Pandas 对 DataFrame 行中的值进行排名
- javascript - 从工作表中获取准确的日期数组
- powershell - 针对 SSAS 执行 XMLA