0

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

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

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

4

1 回答 1

2

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

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

       set
       {
            this._txtResults= value;
             this.RaisePropertyChangedEvent("TxtResults");
        }
    }
于 2013-04-18T20:48:29.453 回答