我有一个数据列表,其中包含代码、名称和其他一些数据的国家/地区。
List<Country> countries = <deserialized objects from file>
Run Code Online (Sandbox Code Playgroud)
由这样的对象组成:
public class Country
{
public string Code { get; set;}
public string Name { get; set;}
}
Run Code Online (Sandbox Code Playgroud)
用作 DataContext 的对象可能如下所示:
public class Address
{
public string StreetName{ get; set;}
public string CountryCode { get; set;}
}
Run Code Online (Sandbox Code Playgroud)
然后在我的 XAML 中,我想做这样的事情来显示国家/地区的名称
<TextBlock Text="{Binding Path=CountryCode, Converter={StaticResource CountryNameLookupConverter}}"/>
Run Code Online (Sandbox Code Playgroud)
但是如何让 CountryNameLookupConverter 使用我从 xml 文件中读取的国家/地区列表?
根据您公开国家集合的位置,有几种不同的选择。
如果国家/地区存在于 Address 或其他一些 ViewModel 对象中,则更改转换器以实现 IMultiValueConverter 而不是 IValueConverter,然后使用 MultiBinding 传递 CountryCode 和国家/地区(作为属性公开)。然后,您将访问并转换 values[0] 和 values[1] 以使用它们在 Convert 方法中进行查找。
<TextBlock>
<TextBlock.Text>
<MultiBinding Converter="{StaticResource CountryNameLookupConverter}">
<Binding Path="CountryCode" />
<Binding Path="Countries" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
Run Code Online (Sandbox Code Playgroud)
如果您静态公开国家/地区(即 Lookup.Countries),您可以将集合作为属性或通过 ConverterParameter 传递给您的 IValueConverter。这是具有属性的转换器:
public class CountryNameLookupConverter : IValueConverter
{
public IEnumerable<Country> LookupList { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Country country = LookupList.FirstOrDefault(c => c.Code.Equals(value));
if (country == null)
return "Not Found";
return country.Name;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return Binding.DoNothing;
}
}
Run Code Online (Sandbox Code Playgroud)
并且转换器资源将被声明为:
<local:CountryNameLookupConverter x:Key="CountryNameLookupConverter" LookupList="{x:Static local:Lookup.Countries}"/>
Run Code Online (Sandbox Code Playgroud)
或者改为传入 Convert 的对象参数:
<TextBlock Text="{Binding Path=CountryCode, Converter={StaticResource CountryNameLookupConverter}, ConverterParameter={x:Static local:Lookup.Countries}}" />
Run Code Online (Sandbox Code Playgroud)