对不起,如果这很难看,但我不明白。我认为问题在于我的xaml,但我不知道。我想要的是在重量文本框中显示180,在高度文本框中显示5。感谢您的任何建议,并让我知道是否需要更多信息。WPF数据绑定工作不正常
这是我MainWindow.xamml.cs
namespace Simple_BMI.Views
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
}
}
这是我MinWindow.xaml
<Window x:Class="Simple_BMI.Views.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="300" Width="300">
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal" VerticalAlignment="Top">
<Label>Weight: </Label>
<TextBox Text="{Binding Model.Weight}" Width="136" />
<Button>Update</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<Label>Height: </Label>
<TextBox Text="{Binding Model.Height}" Width="136" />
</StackPanel>
</StackPanel>
</Window>
我的模型:
namespace Simple_BMI.Models
{
public class Model : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public Model(double weight, double height)
{
Weight = weight;
Height = height;
}
private double _Weight;
public double Weight
{
get
{
return _Weight;
}
set
{
_Weight = value;
OnPropertyChanged("Weight");
}
}
private double _Height;
public double Height
{
get
{
return _Height;
}
set
{
_Height = value;
OnPropertyChanged("Height");
}
}
private void OnPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
我的视图模型:
namespace Simple_BMI.ViewModels
{
class ViewModel
{
public ViewModel()
{
_Measurement = new Model(180, 6);
}
private Model _Measurement;
public Model Measurement
{
get
{
return _Measurement;
}
}
public void SaveChanges()
{
Debug.Assert(false, String.Format("{0} {1} was updated.", Measurement.Weight, Measurement.Height));
}
}
}
使用Measurement.Weight和Measurement.Height在您的XAML而不是Model.Weight和Model.Height – patdhlk