【发布时间】:2014-11-17 19:43:37
【问题描述】:
我有一个在this 答案中使用MethodToValueConverter 的数据绑定。这很好用,但是在方法的结果发生变化后我很难强制更新视图。这有点难以解释,所以希望一些代码片段会有所帮助。
类对象
[DataContract]
public class RetentionBankItem : INotifyPropertyChanged
{
#region Private Properties
public event PropertyChangedEventHandler PropertyChanged;
private float _rbRevisedRateLoad;
private float _rbCurrentRateLoad;
#endregion
[DataMember]
public float rbRevisedRateLoad
{
get
{
return _rbRevisedRateLoad;
}
set
{
PropertyChanged.ChangeAndNotify(ref _rbRevisedRateLoad, value, () => rbRevisedRateLoad);
OnPropertyChanged("RateLoadDifference");
}
}
[DataMember]
public float rbCurrentRateLoad
{
get
{
return _rbCurrentRateLoad;
}
set
{
PropertyChanged.ChangeAndNotify(ref _rbCurrentRateLoad, value, () => rbCurrentRateLoad);
OnPropertyChanged("RateLoadDifference");
}
}
public float RateLoadDifference()
{
if (rbCurrentRateLoad != 0)
{
return rbRevisedRateLoad / rbCurrentRateLoad;
}
return 0;
}
}
需要注意的是,在下面的代码中,RetentionBank的类型是List<RetentionBankItem>
我的绑定看起来像这样:
<ItemsControl ItemsSource="{Binding RetentionBank}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding rbRevisedRateLoad, Mode=TwoWay}"
Grid.Row="2"
Grid.Column="0" />
<TextBox Text="{Binding rbCurrentRateLoad, Mode=TwoWay}"
Grid.Row="2"
Grid.Column="1" />
<TextBox Text="{Binding Path=., Converter={StaticResource ConverterMethodToValue}, ConverterParameter='RateLoadDifference', Mode=OneWay}"
Grid.Row="2"
Grid.Column="2" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
当前和修订的速率负载已正确设置,但在设置后,RateLoadDifference 永远不会被调用更新。我想需要调用类对象本身来更新,因为这是文本框实际绑定的内容(不一定是方法本身),但我不确定如何做到这一点,或者它是否是正确的方法它。任何帮助或建议将不胜感激。谢谢!
【问题讨论】:
-
什么是 PropertyChanged.ChangeAndNotify?
-
它本质上是一种调用
OnPropertyChanged的更简洁(并且由于不使用字符串而对代码更友好)的方式。我从here得到那段代码 -
它是否以常规方式工作 - _rbCurrentRateLoad = value; OnPropertyChanged()?
-
很遗憾没有。当前和修订的速率负载属性设置没有问题,但设置后视图不会使用来自
RateLoadDifference的最新结果进行更新 -
您可能需要一个用于 RateLoadDifference 的吸气剂吗?
标签: c# wpf xaml mvvm data-binding