I have DataGrid
with DataGridComboBoxColumn
column which can be edited. When I edit it exception is thrown. After debugging I found out that Converter
receives DependencyProperty.UnsetValue
and therefore I had to filter it out by returning ""
and this cause to show empty cell.
I tried to google and understand why I get DependencyProperty.UnsetValue
but without luck.
Any ideas?
public UserControl()
{
InitializeComponent();
DataContext = new MyViewModel();
}
public class MyViewModel : ViewModelBase
{
public ObservableCollection<MyItem> MyItems { get; private set; }
public MyViewModel()
{
LoadStates();
}
public void LoadStates()
{
MyItems = new ObservableCollection<MyItem>(DataProvider.GetList());
//...
}
}
public class MyItem
{
public bool Start {get; set;}
}
public class BoolToStatusConverter : IMultiValueConverter
{
private MyViewModel _model;
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
_model = values[0] as MyViewModel ;
//TODO: Why I get UnsetValue??
if (values[1] == DependencyProperty.UnsetValue) return "";
//Using _model
//...
return (bool)values[1] ? Statuses.Start : Statuses.Stop;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
return new object[] { _model, (Statuses)value == Statuses.Start };
}
}
<UserControl.Resources>
<local:BoolToStatusConverter x:Key="BoolToStatusConverter" />
<ObjectDataProvider x:Key="myEnum" MethodName="GetValues" ObjectType="{x:Type core:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type Type="local:Statuses"/>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</UserControl.Resources>
<Grid>
<DataGrid ItemsSource="{Binding MyItems}" AutoGenerateColumns="False" >
<DataGrid.Columns>
<DataGridComboBoxColumn Header="Status" ItemsSource="{Binding Source={StaticResource myEnum}}">
<DataGridComboBoxColumn.SelectedItemBinding>
<MultiBinding Converter="{StaticResource BoolToStatusConverter}">
<Binding Path="DataContext"
RelativeSource="{RelativeSource AncestorType={x:Type UserControl}}" />
<Binding Path="Start" />
</MultiBinding>
</DataGridComboBoxColumn.SelectedItemBinding>
</DataGridComboBoxColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>