Bind to the difference of two Properties from two different ViewModels
I have two viewmodels (each with thier own models): AmendmentViewModel YearViewModel
each have a property: AmendmentViewModel.TotalAmended YearViewModel.TotalCommitted
On the view there is a TabControl and each of the viewmodels is the datacontext for a tabcontrol page. Yes i know I could technically use one view model but its a LOT of code and a larg开发者_如何转开发e view that Has to be in a tabcontrol.
How do i set the binding of a TextBox to the sum of AmendmentViewModel.TotalAmended & YearViewModel.TotalCommitted ?
You can use a MultiBinding
together with an IMultiValueConverter
. You can find an example here.
Edit:
Here's an example:
<Grid>
<Grid.Resources>
<sys:String x:Key="dataSource1">42</sys:String>
<sys:String x:Key="dataSource2">22</sys:String>
<local:SubtractionConverter x:Key="subtractionConverter"/>
</Grid.Resources>
<TextBlock>
<TextBlock.Text>
<MultiBinding Converter="{StaticResource subtractionConverter}">
<Binding Path="." Source="{StaticResource dataSource1}"/>
<Binding Path="." Source="{StaticResource dataSource2}"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</Grid>
and the converter:
public class SubtractionConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
return (double.Parse((string)values[0]) - double.Parse((string)values[1])).ToString();
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
精彩评论