简体   繁体   中英

Update a control based on a property name to which it is not bound

I have some code that calculates several values. Once the calculation is done, I want all affected controls to update.

Easiest to explain with code...

XAML:

<TextBlock x:Name="A" Text="{Binding PropertyA}" />
<TextBlock x:Name="B" Text="{Binding PropertyB}" />

ViewModel:

public decimal PropertyA { get; set; }
public decimal PropertyB { get; set; }

public void CalculateAandB()
{
    PropertyA = 12m;
    PropertyB = 14m;

    PropertyChanged(this, new PropertyChangedEventArgs("Recalculated"));
}

In some way, I would like both A and B to update with their respective new value when the "Recalculated" event is raised.

I would like to do it in XAML, not C# code, and I don't want to replace the whole ViewModel since only a subset of the ViewModel's properties are changed.

Either raise PropertyChanged for every property, which bindings you want to update:

public void CalculateAandB()
{
    PropertyA = 12m;
    PropertyB = 14m;

    PropertyChanged(this, new PropertyChangedEventArgs("PropertyA"));
    PropertyChanged(this, new PropertyChangedEventArgs("PropertyB"));
}

or group properties into separate, nested view model:

class SubViewModel
{
    public decimal PropertyA { get; set; }
    public decimal PropertyB { get; set; }
}

class ViewModel
{
    public SubViewModel SubViewModel { get; set; }

    public void CalculateAandB()
    {
        SubViewModel.PropertyA = 12m;
        SubViewModel.PropertyB = 14m;

        PropertyChanged(this, new PropertyChangedEventArgs("SubViewModel"));
    }
}

<TextBlock x:Name="A" Text="{Binding SubViewModel.PropertyA}" />
<TextBlock x:Name="B" Text="{Binding SubViewModel.PropertyB}" />

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