数据绑定不会更新值

时间:2013-11-15 00:05:35

标签: c# xaml data-binding windows-phone-8

我正在玩数据绑定,我创建了这样的用户控件(视图):

<UserControl>
<Grid x:Name="LayoutRoot" 
      Background="{StaticResource PhoneChromeBrush}" 
      DataContext="{Binding Source={StaticResource ViewModelSampleDataSource}}"
      >
    <Grid.RowDefinitions>
        <RowDefinition Height="1*"/>
        <RowDefinition Height="1*"/>
    </Grid.RowDefinitions>
    <TextBox Text="{Binding Model.Var1, Mode=TwoWay}" InputScope="Number" Grid.Row="0" FontSize="90"/>
    <TextBlock Text="{Binding Model.Var2}" Grid.Row="1" FontSize="90" />
</Grid>

我有这个类Model

 public class ModelSample:INotifyPropertyChanged
{
    public ModelSample()
    {

    }

    private double var1;
    public double Var1
    {
        get { return var1; }
        set 
        { 
            var1 = value;
            OnPropertyChanged("var"); 
        }
    }

    private double var2;
    public double Var2
    {
        get { return var2; }
        set 
        { 
            var2 = value; 
            OnPropertyChanged("var2"); 
        }
    }


    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(name));
    }
}

这是ViewModel

public class ViewModelSample
{
    private static ModelSample model=new ModelSample();
    public static ModelSample Model
    {
        get { return model; }
        set { model = value; }
    }

}

我的问题是:当我更改var1的值(使用文本框)我想更新var2的值时,我该怎么办?感谢

3 个答案:

答案 0 :(得分:1)

用于OnPropertyChanged的字符串值必须与属性名称匹配,而不是与字段名称匹配。修复后只需从Var1的setter内部更改Var2即可。

答案 1 :(得分:0)

更改此

    private double var1;
public double Var1
{
    get { return var1; }
    set 
    { 
        var1 = value;
        OnPropertyChanged("var"); 
    }
}

private double var2;
public double Var2
{
    get { return var2; }
    set 
    { 
        var2 = value; 
        OnPropertyChanged("var2"); 
    }
}

到这个

    private double var1;
public double Var1
{
    get { return var1; }
    set 
    { 
        var1 = value;
        OnPropertyChanged("Var"); 
    }
}

private double var2;
public double Var2
{
    get { return var2; }
    set 
    { 
        var2 = value; 
        OnPropertyChanged("Var2"); 
    }
}

提升属性已更改为其属性名称区分大小写

答案 2 :(得分:0)

试试这个:

private double var1;
public double Var1
{
    get { return var1; }
    set 
    { 
        var1 = value;
        OnPropertyChanged("Var1"); 
    }
}

private double var2;
public double Var2
{
    get { return var2; }
    set 
    { 
        var2 = value; 
        OnPropertyChanged("Var2"); 
    }
}

请注意,OnPropertyChanged字符串必须与属性名称

匹配