【发布时间】:2021-06-26 07:44:08
【问题描述】:
我只是在学习 WPF,最终我想要完成的是数据网格中的计算列,其中显示的数字是集合中特定属性的总和。
经过一番谷歌搜索后,我决定采用的方法是使用 ValueConverter 进行计算,但似乎该数字从未在 UI 中更新。我所做的阅读表明 PropertyChangedEvent 应该冒泡,这应该只是工作,但它没有。我错过了一些东西,但我不知道是什么。
我编写了一个简单的演示应用程序来展示我在下面做什么。第二个TextBlock中的数字在点击按钮之前应该是10(是),但是点击之后是6,但是一直保持在10。
怎么会?我在吠叫错误的树吗?有一个更好的方法吗?任何帮助将不胜感激。
MainWindow.xaml:
<Window x:Class="TestApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:TestApp"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<local:BarSumConverter x:Key="BarSumConverter" />
</Window.Resources>
<StackPanel>
<TextBlock Text="{Binding ObjFoo.Bars[0].ANumber, Mode=TwoWay}" />
<TextBlock Text="{Binding ObjFoo.Bars, Converter={StaticResource BarSumConverter}, Mode=TwoWay}" />
<Button Content="Click me!" Click="Button_Click" />
</StackPanel>
</Window>
MainWindow.xaml.cs
namespace TestApp
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public Foo ObjFoo { get; set; }
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
ObjFoo = new Foo();
ObjFoo.Bars.Add(new Bar(5));
ObjFoo.Bars.Add(new Bar(5));
}
private void Button_Click(object sender, RoutedEventArgs e)
{
ObjFoo.Bars[0].ANumber = 1;
}
}
}
Foo.cs
public class Foo
{
public Foo()
{
bars = new ObservableCollection<Bar>();
}
ObservableCollection<Bar> bars;
public ObservableCollection<Bar> Bars
{
get
{
return bars;
}
set { bars = value; }
}
}
Bar.cs
public class Bar : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public Bar(int number)
{
this.ANumber = number;
}
private int aNumber;
public int ANumber
{
get { return aNumber; }
set
{
aNumber = value;
OnPropertyChanged("aNumber");
}
}
protected void OnPropertyChanged([CallerMemberName] string name = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
BarSumConverter.cs
public class BarSumConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var bars = value as ObservableCollection<Bar>;
if (bars == null) return 0;
decimal total = 0;
foreach (var bar in bars)
{
total += bar.ANumber;
}
return total;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
【问题讨论】:
标签: c# wpf mvvm ivalueconverter