好的。删除所有代码并重新开始。
首先,您在这里有一个严重的误解:The UI is NOT the right place to store data。
因此,您不应该将数值放在 XAML 中,而是应该创建一个适当的 ViewModel 来存储这些数字并对其进行操作:
<Window x:Class="MiscSamples.AverageNumbersSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="AverageNumbersSample" Height="300" Width="300">
<DockPanel>
<Button Content="Calculate" Click="Calculate" DockPanel.Dock="Top"/>
<ListBox ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Value}" x:Name="txt"/>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding IsBelowAverage}" Value="True">
<Setter TargetName="txt" Property="Foreground" Value="Blue"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</DockPanel>
</Window>
代码背后:
public partial class AverageNumbersSample : Window
{
public double Average = 116.21428571428571;
public List<AverageSampleViewModel> Values { get; set; }
public AverageNumbersSample()
{
InitializeComponent();
DataContext = Values = Enumerable.Range(100, 150)
.Select(x => new AverageSampleViewModel() { Value = x })
.ToList();
}
private void Calculate(object sender, RoutedEventArgs e)
{
Values.ForEach(x => x.IsBelowAverage = x.Value < Average);
}
}
数据项:
public class AverageSampleViewModel: PropertyChangedBase
{
public int Value { get; set; }
private bool _isBelowAverage;
public bool IsBelowAverage
{
get { return _isBelowAverage; }
set
{
_isBelowAverage = value;
OnPropertyChanged("IsBelowAverage");
}
}
}
PropertyChangedBase 类(MVVM 助手)
public class PropertyChangedBase:INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
Application.Current.Dispatcher.BeginInvoke((Action) (() =>
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}));
}
}
结果:
- 从这个意义上说,WPF 与当前存在的任何其他东西(例如可用于 java 或类似的东西的多个恐龙古老 UI 框架)根本不同。
- 您绝不能使用 UI 来处理
store 数据,而是使用 UI 来处理 show 数据。这些概念根本不同。
- 我的示例(这是执行 WPF 应用程序的正确方法)不需要
int.Parse() 或任何类似的转换内容,因为 ViewModel 已经具有所需的正确数据类型。