WPF TextBox不会更新为ViewModel中的程序更改

时间:2013-03-16 21:35:15

标签: c# wpf data-binding

我有一个WPF ViewModel

class MainWindowViewModel : INotifyPropertyChanged
    {
        private string _sql;

        public string Sql
        {
            get { return _sql; }
            set
            {
                if (value == _sql) return;
                OnPropertyChanged("Sql");
                _sql = value;
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
}

我还有一个带有TextBox的XAML视图

<Window.Resources>
    <HbmSchemaExporter:MainWindowViewModel x:Key="viewModel"/>
</Window.Resources>
....

<TextBox Grid.Row="6" Grid.Column="0" Grid.ColumnSpan="2" Text="{Binding Source={StaticResource ResourceKey=viewModel}, Path=Sql,Mode=OneWay}"/>

背后的代码

    private MainWindowViewModel ViewModel
    {
        get { return Resources["viewModel"] as MainWindowViewModel; }
    }

问题是,当我在代码中viewModel.Sql = SOMETHING时,文本框不会更新。调试器在属性中显示正确的值,但文本框保持空白。

我也尝试将绑定更改为TwoWay,但这只允许我用文本框中输入的值覆盖属性,这是我不想要的(实际上我还需要制作)它只读,但它目前超出了范围。)

如何以编程方式更新属性后更新文本框?

该应用程序基本上是一个NHibernate DDL生成器,我在阅读this后写的。我需要按“生成SQL”按钮,它会显示运行到DB的代码。

1 个答案:

答案 0 :(得分:4)

public string Sql
{
    get { return _sql; }
    set
    {
        if (value == _sql) return;
        OnPropertyChanged("Sql");
        _sql = value;
    }
}

这没有意义。在调用任何PropertyChanged事件处理程序时,阅读Sql仍将提供旧值,因为您尚未更新_sql。您需要先更新该值,然后才会引发PropertyChanged事件。

相关问题