在ViewModel中更改时,Textblock的文本值不会在View中更新

时间:2013-04-18 20:36:19

标签: c# wpf data-binding textblock

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

    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"); }
    }

现在它正在运作!谢谢。

1 个答案:

答案 0 :(得分:2)

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

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

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