【问题标题】:what's wrong with my databinding?我的数据绑定有什么问题?
【发布时间】:2012-03-13 19:16:54
【问题描述】:

我从空白全景图项目中复制了代码并进行了一些调整,但有些地方不对。

我的文本块设置好了:

<TextBlock Grid.Column="0" Grid.Row="0" Text="{Binding ElementName=CurrentPlaceNow, Path=Temperature}" />

我的模型如下所示:

public class CurrentPlaceNowModel : INotifyPropertyChanged
{
    #region PropertyChanged()
    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(String propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (null != handler)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    #endregion

    private string _temperature;
    public string Temperature
    {
        get
        {
            return _temperature;
        }
        set
        {
            if (value != _temperature)
            {
                _temperature = value;
                NotifyPropertyChanged("Temperature");
            }
        }
    }
}

并定义在MainViewModel():

public CurrentPlaceNowModel CurrentPlaceNow = new CurrentPlaceNowModel();

最后我为按钮点击添加了一个修饰符:

App.ViewModel.CurrentPlaceNow.Temperature = "foo";

现在,为什么文本框中没有显示任何内容?

【问题讨论】:

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


    【解决方案1】:

    您的 Binding 应该在 ViewModel 中导航。绑定到 ElementName 会尝试查看可视树中的另一个对象。

    将您的绑定更改为:

    <TextBlock 
        Grid.Column="0" 
        Grid.Row="0" 
        Text="{Binding CurrentPlaceNow.Temperature}" />
    

    验证您的 ViewModel 的属性格式是否正确:

    private CurrentPlaceNowModel _CurrentPlaceNow = new CurrentPlaceNowModel();
    public CurrentPlaceNowModel CurrentPlaceNow
    {
       get { return _CurrentPlaceNow; }
       set
       {
           _CurrentPlaceNow = value;
           NotifyPropertyChanged("CurrentPlaceNow");
       }
    }
    

    只要您的 View 的 DataContext 是您的 MainViewModel,您就可以开始了。

    【讨论】:

    • 正确,谢谢!完全忘记了 _CurrentPlaceNow 的获取/设置
    【解决方案2】:

    您使用 ElementName 错误。 ElementName 是当您想要绑定到另一个 XAML 控件,而不是(查看)模型时。

    要绑定到模型,将该模型的实例设置为 DataContext 属性并仅绑定 Path。

    【讨论】:

      猜你喜欢
      • 2010-12-16
      • 1970-01-01
      • 2017-12-30
      • 1970-01-01
      • 1970-01-01
      • 2010-11-09
      • 2016-05-22
      • 1970-01-01
      • 2014-04-13
      相关资源
      最近更新 更多