1

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

<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>

我有这个类模型

 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 的值,我该怎么做?谢谢

4

3 回答 3

1

您用于 OnPropertyChanged 的​​字符串值必须与属性名称而不是字段名称匹配。修复后,只需从 Var1 的 setter 中更改 Var2 就可以了。

于 2013-11-15T00:09:09.523 回答
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"); 
    }
}

引发属性更改必须在其属性名称上区分大小写。

于 2013-11-15T00:13:20.267 回答
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 字符串必须与属性的名称匹配

于 2013-11-15T08:37:27.423 回答