我有三个用于存储数值的文本框,以及三个带有我希望绑定到文本框的属性的静态类。我希望第三个文本框等于前两个文本框的总和。我有一个非静态类,它具有所有这些属性(为简单起见,只显示了值):
public class Field : PropertyValueChanged
{
private string _value;
public virtual string Value
{
get { return _value; }
set
{
if (value != _value)
{
_value = value;
NotifyPropertyChanged();
}
}
}
}
然后我有三个静态类:
public static class FirstValueField
{
public static Field FieldProperties;
static FirstValueField()
{
FieldProperties = new Field();
}
}
public static class SecondValueField
{
public static Field FieldProperties;
static SecondValueField()
{
FieldProperties = new Field();
}
}
public static class TotalField
{
public static Field FieldProperties = new Field();
static TotalField()
{
FirstValueField.FieldProperties.PropertyChanged += TotalField_PropertyChanged;
SecondValueField.FieldProperties.PropertyChanged += TotalField_PropertyChanged;
}
private static void TotalField_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
double val1, val2;
if (FirstValueField.FieldProperties.Value == null)
{
val1 = 0;
}
else
{
val1 = Double.Parse(FirstValueField.FieldProperties.Value);
}
if (SecondValueField.FieldProperties.Value == null)
{
val2 = 0;
}
else
{
val2 = Double.Parse(SecondValueField.FieldProperties.Value);
}
FieldProperties.Value = (val1 + val2).ToString();
MessageBox.Show("Changing TotalField to: " + FieldProperties.Value);
}
}
我的xaml看起来像这样:
<TextBox x:Name="FirstValueField"
Text="{Binding Source={x:Static local:FirstValueField.FieldProperties},
Path=Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<TextBox x:Name="SecondValueField"
Text="{Binding Source={x:Static local:SecondValueField.FieldProperties},
Path=Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<TextBox x:Name="TotalField"
Text="{Binding Source={x:Static local:TotalField.FieldProperties},
Path=Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
问题是TotalField.FieldProperties.Value正在更新,但不是文本框文本。我不确定是什么错?
答案 0 :(得分:1)
您无法绑定到某个字段。你需要把它变成一个属性:
public static class FirstValueField
{
public static Field FieldProperties{get; set;} //<-- See this needs to be property
static FirstValueField()
{
FieldProperties = new Field();
}
}
为您的其他课程做同样的事情。