3

我在 WPF 中有一个文本块,它绑定到我的 ViewModel 类中的一个属性。单击按钮时,我希望修改属性并希望将其反映在我的文本块中。我希望所有这些都完全使用 MVVM (MVVMLight) 来完成。我正在使用 MMVM light 和 VS 2012。挑战 - 单击按钮上的更改未反映。虽然程序执行在属性内部,但没有进行更改。

请帮忙 !!

程序视图:

<Window x:Class="MvvmLight1_Trail.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:ignore="http://www.ignore.com"
    mc:Ignorable="d ignore"
    Height="500"
    Width="500"
    Title="MVVM Light Application"
    DataContext="{Binding Main, Source={StaticResource Locator}}">



<Grid x:Name="LayoutRoot">


    <TextBlock FontSize="34"
               Text="{Binding Path=MyText,UpdateSourceTrigger=Default, Mode=TwoWay}"
               VerticalAlignment="Center"
               HorizontalAlignment="Center"
               TextWrapping="Wrap" />
    <Button Width="100" Height="100" Command="{Binding PressCommand}" Margin="198.985,277.537,193.014,92.462" Content="Press Me"/>

</Grid>

查看模型

using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using MvvmLight1_Trail.Model;
using System.ComponentModel;
using System.Threading;

namespace MvvmLight1_Trail.ViewModel
{

public class MainViewModel : ViewModelBase
{



    public RelayCommand PressCommand { get; private set; }
    Thread t;
    private string _welcomeTitle = string.Empty;


    public string MyText
    {
        get
        {
            return _welcomeTitle;
        }

        set
        {
            if (_welcomeTitle == value)
            {
                return;
            }

            _welcomeTitle = value;
            RaisePropertyChanged(MyText);
        }
    }

    /// <summary>
    /// Initializes a new instance of the MainViewModel class.
    /// </summary>
    public MainViewModel()
    {
        PressCommand = new RelayCommand(() => MyFunc());
        myfunc();
    }

    private void MyFunc()
    {
        this.MyText = "Hi2";
    }

    private void myfunc()
    {

        this.MyText = "Hello";
        this.MyText = "Hi";

    }
}
}
4

3 回答 3

7

代替

RaisePropertyChanged(MyText);

RaisePropertyChanged("MyText");

PropertyChanged 事件应该在属性名称而不是属性值上引发。

于 2013-11-10T10:56:41.807 回答
4

@Rohit Vats 已经回答了。您也可以调用 RaisePropertyChanged 之类的方法,RaisePropertyChanged( () => MyText)以便稍后重命名。

于 2013-11-10T10:56:27.103 回答
1

比赛迟到了,但是:

在新的 C# 6 中,您还可以像这样使用 nameof:

RaisePropertyChanged(nameof(MyText))
于 2017-03-26T13:48:42.603 回答