I have a table which has two columns ValueA
and ValueB
. I need to show the table in a grid, but I need to show either ValueA
or ValueB
, but not both. So if ValueA
doesn't have a value, then ValueB
is shown and vice versa. When user enters a value to the column, only ValueA
should be updated. So ValueB
in kind of a default value (it's update in another part of the program).
I've tried to resolve this problem using MultiBinding
, but I've only managed to show the values. The value user enters to the grid always gets overwritten by the original value.
I have created a converter named ValueAValueBConverter
that has a Convert method like this:
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (values[0] != DependencyProperty.UnsetValue && values[0] != null && !string.IsNullOrEmpty(values[0].ToString()))
{
Debug.WriteLine("values 0: " + values[0]);
return values[0].ToString();
}
if (values[1] != DependencyProperty.UnsetValue && values[1] != null && !string.IsNullOrEmpty(values[1].ToString()))
{
Debug.WriteLine("values 1: " + values[1]);
return values[1].ToString();
}
return null;
}
And a ConvertBack method (which never gets called):
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
return new object [] { value, value };
}
The XAML of the bound colums looks like this:
<toolkit:DataGridTextColumn Width="2*" Header="{x:Static localProperties:Resources.TValuesAB}">
<toolkit:DataGridTextColumn.Binding>
<MultiBinding Converter="{StaticResource myValueAValueBConverter}" Mode="TwoWay">
<Binding Path="ValueA" UpdateSourceTrigger="PropertyChanged" />
<Binding Path="ValueB" UpdateSourceTrigger="PropertyChanged" />
</MultiBinding>
</toolkit:DataGridTextColumn.Binding>
</toolkit:DataGridTextColumn>
Should I do this in the ViewModel (we're using MVVM pattern) or is there any other way to do this with XAML?
If I well understood, you just need one attribute more in your class, something like ValueAorB. With a getter which will do the work your Converter does and a setter a bit more complicated.
public object ValueAorB
{
get
{
if (values[0] != DependencyProperty.UnsetValue && values[0] != null && !string.IsNullOrEmpty(values[0].ToString()))
{
Debug.WriteLine("values 0: " + values[0]);
return values[0].ToString();
}
if (values[1] != DependencyProperty.UnsetValue && values[1] != null && !string.IsNullOrEmpty(values[1].ToString()))
{
Debug.WriteLine("values 1: " + values[1]);
return values[1].ToString();
}
}
}
Don't forget to make it raises the PropertyChanged event.
And with that:
And a ConvertBack method (which never gets called):
May be you don't need a setter. Think about it. A two way will be more complicated and you don't even need it. In addition, I think you could do it with your own method if you were trying to make it one way.