简体   繁体   中英

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 large 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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM