如果在代码(WPF)中更改变量,则在XAML中绑定不起作用



我是在C#和XAML中编码的新手,我只是无法在XAML中使用绑定。当我初始化演示者类时,它曾经有效一次,但是如果我更改代码中的界变量,则不会更新文本框文本。

当程序启动时," 200"显示在文本框中。如果我按下按钮,所有消息框将显示(显示" 100"(,但是文本框仍然显示" 200",而不是" 100"。

我尝试了在网上找到的许多解决方案,但似乎都没有起作用。

主持人类(ViewModel(:

class Presenter : ObservableObject
{        
    float _xText;
    public float xText
    {
        get { return _xText; }
        set
        {
            _xText = value;
            RaisePropertyChangedEvent("xText");
        }
    }        
    public ICommand Update
    {
        get { return new DelegateCommand(_Update); } 
    }
    public Presenter()
    {
        _xText = 200f;
    }
    void _Update()
    {
        MessageBox.Show("_Update");
        _xText = 100f;
        //Debug
        MessageBox.Show(_xText.ToString());
        MessageBox.Show(xText.ToString());
    }
}

XAML代码(视图(:

 <TextBox IsReadOnly="False" 
          IsEnabled="True" 
          Text="{Binding Path=xText, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
 <Button Command="{Binding Update}"/>

可观察到的类别:

public abstract class ObservableObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected void RaisePropertyChangedEvent(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }  
    }
}

我希望有人有解决方案或可以解释我出错的地方。谢谢。

您正在更新衬板,而不是属性,因此没有调用NotifyPropertychanged。改用属性

void _Update()
{
    MessageBox.Show("_Update");
    xText = 100f;
    //Debug
    MessageBox.Show(_xText.ToString());
    MessageBox.Show(xText.ToString());
}

解决您的问题:

  1. 您正在设置Backing变量_XTEXT,以免运行属性Xtext。(如 @ken-tucker所说(

(额外更改(

  1. 我从不在C#或(SQL Server(数据库中使用Float。(您会后悔的。(

请参阅此处"小数,双和浮子之间的区别"。

  1. 查看是否可以替换:

    RaisePropertyChangedEvent("xText"); 
    

    RaisePropertyChanged(() => xText);
    

您将避免很多被错别字刺痛的情况。

  1. 您有一个名为Xtext的属性?希望这只是一个问题,否则不好。您正在为读者写作。从命名指南开始。

相关内容

最新更新