[英]Update a control based on a property name to which it is not bound
我有一些代码可以计算多个值。 一旦计算完成,我希望所有受影响的控件都进行更新。
最容易用代码解释...
XAML:
<TextBlock x:Name="A" Text="{Binding PropertyA}" />
<TextBlock x:Name="B" Text="{Binding PropertyB}" />
视图模型:
public decimal PropertyA { get; set; }
public decimal PropertyB { get; set; }
public void CalculateAandB()
{
PropertyA = 12m;
PropertyB = 14m;
PropertyChanged(this, new PropertyChangedEventArgs("Recalculated"));
}
以某种方式,当引发"Recalculated"
事件时,我希望A和B都使用各自的新值进行更新。
我想用XAML而不是C#代码来做,而且我不想替换整个ViewModel,因为只更改了ViewModel属性的一个子集。
为每个属性(您要更新的绑定)提高PropertyChanged
:
public void CalculateAandB()
{
PropertyA = 12m;
PropertyB = 14m;
PropertyChanged(this, new PropertyChangedEventArgs("PropertyA"));
PropertyChanged(this, new PropertyChangedEventArgs("PropertyB"));
}
或将属性分为单独的嵌套视图模型:
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}" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.