我是WPF和C#的新手,所以请帮助解决这个问题。
我有一个DataGrid
列,如下所示:“One”,“Two”,“Multiply”。
我输入数字“One”或“Two”的想法,并在“Multiply”列中得到结果。
当我编写代码并对其进行调试时,我可以看到正在重新计算属性的值。但是,除非我按空格键或点击我的上一栏,否则我不会显示在我的上一栏中。
以下是代码:
public class Numbers : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private double _one;
private double _two;
private double _multiply;
public double One
{
get { return _one; }
set { _one = value; UpdateValue(); }
}
public double Two
{
get { return _two; }
set { _two = value; UpdateValue(); }
}
public double Multiply
{
get { return _multiply; }
set { _multiply = value; UpdateValue(); }
}
public Numbers(double pOne, double pTwo)
{
_one = pOne;
_two = pTwo;
_multiply = GetMultiply();
}
private void UpdateValue()
{
OnPropertyChanged("One");
OnPropertyChanged("Two");
OnPropertyChanged("Multiply");
_multiply = GetMultiply();
}
private double GetMultiply()
{
return _one * _two;
}
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
public class Collection : ObservableCollection<Numbers>
{
public ObservableCollection<Numbers> Numbers { get; set; }
public Collection()
{
Numbers = new ObservableCollection<Numbers>();
Numbers.Add(new Numbers(1, 2));
Numbers.Add(new Numbers(2, 2));
}
}
XAML:
<DataGrid x:Name="StockData" HorizontalAlignment="Left" Margin="0,0,0,0" VerticalAlignment="Top" ItemsSource="{Binding}" AutoGenerateColumns="False" LostFocus="StockData_LostFocus" >
<DataGrid.Columns >
<DataGridTextColumn Header="Number One" Width="100" Binding="{Binding One, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, StringFormat=\{0:C\}}" />
<DataGridTextColumn Header="Number Two" Width="100" Binding="{Binding Two, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, StringFormat=\{0:C\}}" />
<DataGridTextColumn Header="Total" Width="100" Binding="{Binding Multiply, BindsDirectlyToSource=True, Mode=TwoWay, StringFormat=\{0:C\}, UpdateSourceTrigger=PropertyChanged}" />
</DataGrid.Columns>
</DataGrid>
答案 0 :(得分:2)
您在提升PropertyChanged事件后设置为multip,因此UI不会收到值已更改的通知。
设置乘法然后提升PropertyChanged事件:
private void UpdateValue()
{
_multiply = GetMultiply();
OnPropertyChanged("One");
OnPropertyChanged("Two");
OnPropertyChanged("Multiply");
}