【问题标题】:Textblock's text value not updating in View when changed in ViewModel在 ViewModel 中更改时,Textblock 的文本值未在 View 中更新
【发布时间】:2013-04-18 20:36:18
【问题描述】:

我使用命令创建了一个提交按钮,该命令根据用户是否在文本框中输入了正确的数字来更改文本块中的文本。

    public string txtResults { get; set; }
    public string txtInput { get; set; }

        // Method to execute when submit command is processed
    public void submit() 
    {
        if (txtInput == number.ToString())
            txtResults = "Correct!";
        else
            txtResults = "Wrong!";
    }

'txtInput' 是绑定到文本框并包含用户输入的成员。 'txtResults' 应该显示在文本块中。现在,当我单击提交按钮时,在调试模式下,txtResults 值被分配为“正确!”字符串,但它不会在视图中更新。

XAML:

<Window x:Class="WpfMVVP.WindowView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfMVVP"
    Title="Window View" Height="350" Width="525" Background="White">
<Grid>
    <Canvas>
        <Label Canvas.Left="153" Canvas.Top="89" Content="Guess a number between 1 and 5" Height="28" Name="label1" />
        <TextBox   Text="{Binding txtInput, UpdateSourceTrigger=PropertyChanged}" Canvas.Left="168" Canvas.Top="142" Height="23" Name="textBox1" Width="38" />
        <TextBlock Text="{Binding txtResults}" Canvas.Left="257" Canvas.Top="142" Height="23" Name="textBlock1" />
        <Button Command="{Binding Submit}" Canvas.Left="209" Canvas.Top="197" Content="Submit" Height="23" Name="button1" Width="75" />
    </Canvas>
</Grid>

更新:

我在我的视图模型中进行了此更改

public class WindowViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }


    private string _txtResults;
    public string txtResults
    {
        get { return _txtResults; }
        set { _txtResults = value; OnPropertyChanged("txtResults"); }
    }

现在它开始工作了!谢谢。

【问题讨论】:

  • 发布 XAML 和这些属性的定义(txtResults 和 txtInput)。\

标签: c# wpf data-binding textblock


【解决方案1】:

请确保您的 txtResults 属性继承自 INotifyPropertyChanged。您的视图模型也应该从那里继承。让您的视图模型类从 INotifyPropertyChanged 继承,并实现接口。然后将您的 TxtResults 属性替换为以下内容:

    private string _txtResults = string.Empty;
    public string TxtResults
    {
        get { return this._txtResults; }

       set
       {
            this._txtResults= value;
             this.RaisePropertyChangedEvent("TxtResults");
        }
    }

【讨论】:

    猜你喜欢
    • 2015-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多