在WPF中,可以使用IValueConverter或IMultiValueConverter将数据绑定值从int转换为Color.。
我有一个模型对象的集合,我想将它们转换成它们的ViewModel表示,但在这个场景中,
<ListBox ItemsSource="{Binding ModelItems,
Converter={StaticResource ModelToViewModelConverter}" />转换器将被编写为一次转换整个集合ModelItems。
我希望单独转换集合中的项,有什么方法可以做到吗?我可能想要使用CollectionViewSource并有一些过滤逻辑,这样我就不想每次发生变化时都要遍历整个集合。
发布于 2011-09-22 03:50:03
您不能在集合本身上设置转换器,因为它将获取集合作为输入。您有两个选择:
如果你想使用第二种方法,那么使用类似下面这样的方法:
<ListBox ItemsSource="{Binding ModelItems}">
<ListBox.ItemTemplate>
<DataTemplate>
<ContentPresenter Content="{Binding Converter={StaticResource ModelToViewModelConverter}}"
ContentTemplate="{StaticResource MyOptionalDataTemplate}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>如果不需要自定义数据模板,那么可以跳过ContentTemplate属性。
发布于 2011-09-22 04:28:59
是的你可以。它的行为与IValueConverter相同。您只需将Convert方法的value参数视为一个集合。
下面是一个集合的Converter示例:
public class DataConvert : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
ObservableCollection<int> convertible = null;
var result = value as ObservableCollection<string>;
if (result != null)
{
convertible = new ObservableCollection<int>();
foreach (var item in result)
{
if (item == "first")
{
convertible.Add(1);
}
else if (item == "second")
{
convertible.Add(2);
}
else if (item == "third")
{
convertible.Add(3);
}
}
}
return convertible;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}在这种情况下,这只是一个概念的证明,但我认为它应该很好地展示了这个想法。Converter从一个简单的字符串集合进行转换,如下所示:
ModelItems = new ObservableCollection<string>();
ModelItems.Add("third");
ModelItems.Add("first");
ModelItems.Add("second");转换为与字符串含义相对应的整数集合。
下面是对应的XAML (loc是当前程序集的引用,其中是转换器):
<Window.Resources>
<loc:DataConvert x:Key="DataConverter"/>
</Window.Resources>
<Grid x:Name="MainGrid">
<ListBox ItemsSource="{Binding ModelItems, Converter={StaticResource DataConverter}}"/>
</Grid>如果你想进行双向绑定,你还必须实现转换回。从使用MVVM的经验来看,我建议使用类似工厂模式的东西来从ViewModel中的模型向后转换。
发布于 2018-01-23 15:44:45
这是另一个例子。我正在使用MVVM Caliburn Micro。在我的例子中,MyObjects是一个枚举列表。
<ListBox x:Name="MyObjects">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding ., Converter={StaticResource MyConverter}}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>https://stackoverflow.com/questions/7505524
复制相似问题