我正在构建一个带有组合框和数据网格的wpf表单。组合框绑定到模型基类moWeek的集合。所选项目绑定到一个被称为wm的被驱动类,如SelectedItem="{Binding Week, Mode=TwoWay}"
,而它只是Viewmodel类中vm
类型的属性。
现在当我从组合框中选择一个值时,我得到一个名为TypeConverter的System.NotSupportedException,无法转换model.moWeek。
我想我需要从moWeek到vmWeek的某种转换器,但我不知道在哪里以及如何使用它。我该怎么做?
以下是代码:
模特周课程:
using System.Collections.ObjectModel;
namespace Model
{
public class moWeek
{
public moWeek()
{
}
private int id;
public int Id
{
get { return id; }
set { id = value; }
}
}
}
Viewmodel周课程:
using System;
using System.ComponentModel;
using Model;
using ViewModel.Lists;
namespace ViewModel.Planning
{
public class vmWeek : moWeek
{
private ProjectList projects;
public ProjectList Projects
{
get { return projects; }
set { projects = value; OnPropertyChanged(new PropertyChangedEventArgs("Projects")); }
}
private void OnPropertyChanged(PropertyChangedEventArgs propertyChangedEventArgs)
{
throw new NotImplementedException();
}
}
}
视图模型
using System.ComponentModel;
using tegViewModel.Auswahllisten;
namespace tegViewModel.Planning
{
public class vmPlanning : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public vmPlanning()
{
Weeks = new alWeeks(); //Collection of moWeek
}
public alWeeks Weeks { get; set; }
private vmWeek week;
public vmWeek Week
{
get { return Week; }
set { Week = value; OnPropertyChanged(new PropertyChangedEventArgs("Week")); }
}
private void OnPropertyChanged(PropertyChangedEventArgs propertyChangedEventArgs)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyChangedEventArgs.PropertyName));
}
}
}
}
答案 0 :(得分:1)
首先,您需要创建一个实现接口IValueConverter
[ValueConversion(typeof(moWeek), typeof(vmWeek))]
class MoWeekToVmWeekConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var moweek = value as moWeek;
vmWeek result = //Do your conversion;
return result;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return (moWeek) value;
}
}
之后,您可以在资源中声明该类的实例。
<local:MoWeekToVmWeekConverter x:Key="MoWeekConverter"></local:MoWeekToVmWeekConverter>
声明转换后,您可以在绑定中使用它。
<ComboBox SelectedItem="{Binding Week, Mode=TwoWay, Converter={StaticResource MoWeekConverter}}"></ComboBox>