【发布时间】:2014-08-13 00:53:24
【问题描述】:
我正在动态创建两个文本框和一个文本块。用户首先单击添加一行控件的按钮,然后在每个文本框中输入数字。给定行的两个框的总和将显示在文本块中。
这是 XAML。
<Window x:Class="ModelBuilder_080614.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ModelBuilder_080614"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<!-- this is a comment -->
<local:MainWindowViewModel />
</Window.DataContext>
<Canvas>
<Button Canvas.Top="21" Canvas.Left="20" Content="Add TextBox" Command="{Binding TestCommand}"/>
<ItemsControl Canvas.Top="50" Canvas.Left="50" ItemsSource="{Binding SomeCollection}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid >
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0" Grid.Row="0" Text="{Binding Path=.}"/>
<TextBox Grid.Column="1" Grid.Row="0" Name="Bench" Text="{Binding Path=.}"/>
<TextBlock Grid.Column="2" Grid.Row="0" Text="{Binding <!-- I'm LOST -->}"/>
<!-- I want this TextBlock to sum the Two TextBlocks -->
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Canvas>
</Window>
这是我的 C# 模型和视图模型。
using System;
using System.ComponentModel;
using System.Windows.Input;
using System.Collections.ObjectModel;
using System.Windows.Controls;
using System.Windows.Data;
using MicroMvvm;
namespace ModelBuilder_080614
{
public class MainWindowViewModel
{
public ObservableCollection<Model> SomeCollection { get; set; }
public ICommand TestCommand { get; private set; }
public MainWindowViewModel()
{
SomeCollection = new ObservableCollection<Model>();
TestCommand = new RelayCommand<object>(CommandMethod);
}
private void CommandMethod(object parameter)
{
SomeCollection.Add(new Model());
}
}
public class Model : INotifyPropertyChanged
{
double _actual;
double _bench;
double _active;
public double Actual
{
get { return _actual; }
set { _actual = value; }
}
public double Bench
{
get { return _bench; }
set { _bench = value; }
}
public double Active
{
get { return _active; }
set { _active = Actual - Bench; }
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
如何绑定文本框的内容以在TextBlock中显示它们的总和?
【问题讨论】: