Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Wpf 使用MVVM Light的消息传递问题_Wpf_Mvvm_.net 4.0_Mvvm Light - Fatal编程技术网

Wpf 使用MVVM Light的消息传递问题

Wpf 使用MVVM Light的消息传递问题,wpf,mvvm,.net-4.0,mvvm-light,Wpf,Mvvm,.net 4.0,Mvvm Light,最初我想在两个虚拟机之间传递一个“ObservableCollection”,但即使是简单的消息传递也不适合我 MainViewModel private void openNewSpecialCustomer() { GalaSoft.MvvmLight.Messaging.Messenger.Default.Send("Musaab"); Console.WriteLine("send done"); AddNewSpecialCus

最初我想在两个虚拟机之间传递一个“ObservableCollection”,但即使是简单的消息传递也不适合我

MainViewModel

 private void openNewSpecialCustomer()
    {
        GalaSoft.MvvmLight.Messaging.Messenger.Default.Send("Musaab");
        Console.WriteLine("send done");
        AddNewSpecialCustomer a = new AddNewSpecialCustomer();
        _dialogService.showDialoge(a);
    }
public AddNewSpecialCustomerViewModel()
    {
        GalaSoft.MvvmLight.Messaging.Messenger.Default.Register<string>(this,  doSomething);
        Console.WriteLine("Should now Receive");
        validProperties = new Dictionary<string, bool>();
        validProperties.Add("specialCustomerName",false);
        validProperties.Add("tel", false);
        allPropertiesValid = false;

    }

    public void doSomething(string s)
    {
        Console.WriteLine("Should be received");
        specialCustomerName = s;
        Console.WriteLine("s value " + s);
    }

    public String specialCustomerName
    {
        get { return _specialCustomerName; }
        set
        {
            if (_specialCustomerName != value)
            {
                _specialCustomerName = value;
               OnPropertyChanged("specialCustomerName");

            }
        }
    }
public class MainViewModel : ViewModelBase
{
    public MainViewModel() {
        if (IsInDesignMode) {
            // Code runs in Blend --> create design time data.
        } else {
            // Code runs "for real"
        }
        Messenger.Default.Send("Initializer - does not show becaus of race condition!");
    }

    public string Welcome {
        get {
            return "Welcome to MVVM Light";
        }
    }

    #region [TestCommand]

    private RelayCommand _cmdTest;

    public RelayCommand TestCommand {
        get {
            return _cmdTest ?? (
                _cmdTest = new RelayCommand(
                    () => {
                        // Execute delegate
                        Messenger.Default.Send("Hello!");
                    }
                )
            );
        }
    }

    #endregion

    public override void Cleanup() {
        // Clean up if needed

        base.Cleanup();
    }
}
    public SecondViewModel() {
        Messenger.Default.Register<string>(this, (s) => this.DoSomething(s));

        if (IsInDesignMode) {
            // Code runs in Blend --> create design time data.
        } else {
            // Code runs "for real": Connect to service, etc...
        }
    }

    #region [Message]

    public const string MessagePropertyName = "Message";

    private string _message = default(string);

    public string Message {
        get {
            return _message;
        }

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

            _message = value;

            RaisePropertyChanged(MessagePropertyName);
        }
    }

    #endregion

    public void DoSomething(string s) {
        this.Message = s;
    }

    public override void Cleanup() {
        base.Cleanup();
    }

}
AddNewSpecialCustomerViewModel

 private void openNewSpecialCustomer()
    {
        GalaSoft.MvvmLight.Messaging.Messenger.Default.Send("Musaab");
        Console.WriteLine("send done");
        AddNewSpecialCustomer a = new AddNewSpecialCustomer();
        _dialogService.showDialoge(a);
    }
public AddNewSpecialCustomerViewModel()
    {
        GalaSoft.MvvmLight.Messaging.Messenger.Default.Register<string>(this,  doSomething);
        Console.WriteLine("Should now Receive");
        validProperties = new Dictionary<string, bool>();
        validProperties.Add("specialCustomerName",false);
        validProperties.Add("tel", false);
        allPropertiesValid = false;

    }

    public void doSomething(string s)
    {
        Console.WriteLine("Should be received");
        specialCustomerName = s;
        Console.WriteLine("s value " + s);
    }

    public String specialCustomerName
    {
        get { return _specialCustomerName; }
        set
        {
            if (_specialCustomerName != value)
            {
                _specialCustomerName = value;
               OnPropertyChanged("specialCustomerName");

            }
        }
    }
public class MainViewModel : ViewModelBase
{
    public MainViewModel() {
        if (IsInDesignMode) {
            // Code runs in Blend --> create design time data.
        } else {
            // Code runs "for real"
        }
        Messenger.Default.Send("Initializer - does not show becaus of race condition!");
    }

    public string Welcome {
        get {
            return "Welcome to MVVM Light";
        }
    }

    #region [TestCommand]

    private RelayCommand _cmdTest;

    public RelayCommand TestCommand {
        get {
            return _cmdTest ?? (
                _cmdTest = new RelayCommand(
                    () => {
                        // Execute delegate
                        Messenger.Default.Send("Hello!");
                    }
                )
            );
        }
    }

    #endregion

    public override void Cleanup() {
        // Clean up if needed

        base.Cleanup();
    }
}
    public SecondViewModel() {
        Messenger.Default.Register<string>(this, (s) => this.DoSomething(s));

        if (IsInDesignMode) {
            // Code runs in Blend --> create design time data.
        } else {
            // Code runs "for real": Connect to service, etc...
        }
    }

    #region [Message]

    public const string MessagePropertyName = "Message";

    private string _message = default(string);

    public string Message {
        get {
            return _message;
        }

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

            _message = value;

            RaisePropertyChanged(MessagePropertyName);
        }
    }

    #endregion

    public void DoSomething(string s) {
        this.Message = s;
    }

    public override void Cleanup() {
        base.Cleanup();
    }

}
public addnewspecialcustomservicewmodel()
{
GalaSoft.MvvmLight.Messaging.Messenger.Default.Register(this,doSomething);
Console.WriteLine(“现在应该接收”);
validProperties=新字典();
validProperties.Add(“specialCustomerName”,false);
有效财产。添加(“电话”,假);
allPropertiesValid=false;
}
公共无效剂量测定(字符串s)
{
Console.WriteLine(“应接收”);
specialCustomerName=s;
控制台写入线(“s值”+s);
}
公共字符串specialCustomerName
{
获取{return\u specialCustomerName;}
设置
{
if(_specialCustomerName!=值)
{
_specialCustomerName=值;
OnPropertyChanged(“特殊客户名称”);
}
}
}
现在是AddNewsSpecialCustomer的XAML

<Window FlowDirection="RightToLeft" x:Class="GlassStore.AddNewSpecialCustomer"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:local="clr-namespace:GlassStore.ViewModels"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="AddNewSpecialCustomer" Height="318" Width="458">

<Window.DataContext>
    <local:AddNewSpecialCustomerViewModel/>
</Window.DataContext>
<Grid Background="{DynamicResource NormalBrush}">
    <Button Command="{Binding Save}" Content="موافق" Height="29" HorizontalAlignment="Left" Margin="31,218,0,0" Name="button1" VerticalAlignment="Top" Width="75" />
    <Label Content="إسم العميل" Height="27" HorizontalAlignment="Left" Margin="12,12,0,0" Name="label1" VerticalAlignment="Top" Width="120" />
    <TextBox Text="{Binding specialCustomerName,Mode=TwoWay,ValidatesOnDataErrors=True,ValidatesOnExceptions=True,UpdateSourceTrigger=PropertyChanged}" Height="27" HorizontalAlignment="Left" Margin="155,12,0,0" Name="textBox1" VerticalAlignment="Top" Width="210" />
    <Label Content="المنطقة/المكان" Height="27" HorizontalAlignment="Left" Margin="12,67,0,0" Name="label2" VerticalAlignment="Top" Width="120" />
    <TextBox Text="{Binding region}" Height="27" HorizontalAlignment="Left" Margin="155,67,0,0" Name="textBox2" VerticalAlignment="Top" Width="210" />
    <TextBox Text="{Binding tel,ValidatesOnDataErrors=True,ValidatesOnExceptions=True,UpdateSourceTrigger=PropertyChanged}" Height="27" HorizontalAlignment="Left" Margin="155,119,0,0" Name="textBox3" VerticalAlignment="Top" Width="210" />
    <Label Content="رقم الهاتف " Height="27" HorizontalAlignment="Left" Margin="12,119,0,0" Name="label3" VerticalAlignment="Top" Width="120" />
    <Button Content="إلغاء" Height="29" HorizontalAlignment="Left" Margin="143,218,0,0" Name="button2" VerticalAlignment="Top" Width="75" />
    <Label Content="" Height="29" HorizontalAlignment="Left" Margin="12,177,0,0" Name="label4" VerticalAlignment="Top" Width="412" />
</Grid>

你可以看到有一个文本框,文本属性绑定到specialCustomerName属性,我正试图通过messenger更改它,数据绑定模式是双向的,所以我希望我的文本框在加载时有我的名字,(我通过messenger发送我的名字),但事实并非如此,我希望这可能是更清晰的代码


提前感谢

因为消息的发送和接收都发生在构造函数中,这可能会导致竞争条件。在构造函数中注册接收消息,但在稍后的时间点发送消息,例如在加载或命令处理程序中

编辑

public class ViewModelLocator
{
    private static MainViewModel _main;

    public ViewModelLocator() {
        CreateMain();
    }

    public static MainViewModel MainStatic {
        get {
            if (_main == null) {
                CreateMain();
            }

            return _main;
        }
    }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
        "CA1822:MarkMembersAsStatic",
        Justification = "This non-static member is needed for data binding purposes.")]
    public MainViewModel Main {
        get {
            return MainStatic;
        }
    }

    public static void ClearMain() {
        if (_main != null) {
            _main.Cleanup();
            _main = null;
        }
    }

    public static void CreateMain() {
        if (_main == null) {
            _main = new MainViewModel();
        }
    }

    #region [SecondViewModel]

    private static SecondViewModel _secondViewModel;

    public static SecondViewModel SecondViewModelStatic {
        get {
            if (_secondViewModel == null) {
                CreateSecondViewModel();
            }

            return _secondViewModel;
        }
    }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
        "CA1822:MarkMembersAsStatic",
        Justification = "This non-static member is needed for data binding purposes.")]
    public SecondViewModel SecondViewModel {
        get {
            return SecondViewModelStatic;
        }
    }

    public static void ClearSecondViewModel() {
        if (_secondViewModel != null) {
            _secondViewModel.Cleanup();
            _secondViewModel = null;
        }
    }

    public static void CreateSecondViewModel() {
        if (_secondViewModel == null) {
            _secondViewModel = new SecondViewModel();
        }
    }

    #endregion

    public static void Cleanup() {
        ClearMain();
        ClearSecondViewModel();
    }
}
无法重现该行为,以下是我用来测试该行为的代码:

视图定位器

public class ViewModelLocator
{
    private static MainViewModel _main;

    public ViewModelLocator() {
        CreateMain();
    }

    public static MainViewModel MainStatic {
        get {
            if (_main == null) {
                CreateMain();
            }

            return _main;
        }
    }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
        "CA1822:MarkMembersAsStatic",
        Justification = "This non-static member is needed for data binding purposes.")]
    public MainViewModel Main {
        get {
            return MainStatic;
        }
    }

    public static void ClearMain() {
        if (_main != null) {
            _main.Cleanup();
            _main = null;
        }
    }

    public static void CreateMain() {
        if (_main == null) {
            _main = new MainViewModel();
        }
    }

    #region [SecondViewModel]

    private static SecondViewModel _secondViewModel;

    public static SecondViewModel SecondViewModelStatic {
        get {
            if (_secondViewModel == null) {
                CreateSecondViewModel();
            }

            return _secondViewModel;
        }
    }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
        "CA1822:MarkMembersAsStatic",
        Justification = "This non-static member is needed for data binding purposes.")]
    public SecondViewModel SecondViewModel {
        get {
            return SecondViewModelStatic;
        }
    }

    public static void ClearSecondViewModel() {
        if (_secondViewModel != null) {
            _secondViewModel.Cleanup();
            _secondViewModel = null;
        }
    }

    public static void CreateSecondViewModel() {
        if (_secondViewModel == null) {
            _secondViewModel = new SecondViewModel();
        }
    }

    #endregion

    public static void Cleanup() {
        ClearMain();
        ClearSecondViewModel();
    }
}
MainViewModel

 private void openNewSpecialCustomer()
    {
        GalaSoft.MvvmLight.Messaging.Messenger.Default.Send("Musaab");
        Console.WriteLine("send done");
        AddNewSpecialCustomer a = new AddNewSpecialCustomer();
        _dialogService.showDialoge(a);
    }
public AddNewSpecialCustomerViewModel()
    {
        GalaSoft.MvvmLight.Messaging.Messenger.Default.Register<string>(this,  doSomething);
        Console.WriteLine("Should now Receive");
        validProperties = new Dictionary<string, bool>();
        validProperties.Add("specialCustomerName",false);
        validProperties.Add("tel", false);
        allPropertiesValid = false;

    }

    public void doSomething(string s)
    {
        Console.WriteLine("Should be received");
        specialCustomerName = s;
        Console.WriteLine("s value " + s);
    }

    public String specialCustomerName
    {
        get { return _specialCustomerName; }
        set
        {
            if (_specialCustomerName != value)
            {
                _specialCustomerName = value;
               OnPropertyChanged("specialCustomerName");

            }
        }
    }
public class MainViewModel : ViewModelBase
{
    public MainViewModel() {
        if (IsInDesignMode) {
            // Code runs in Blend --> create design time data.
        } else {
            // Code runs "for real"
        }
        Messenger.Default.Send("Initializer - does not show becaus of race condition!");
    }

    public string Welcome {
        get {
            return "Welcome to MVVM Light";
        }
    }

    #region [TestCommand]

    private RelayCommand _cmdTest;

    public RelayCommand TestCommand {
        get {
            return _cmdTest ?? (
                _cmdTest = new RelayCommand(
                    () => {
                        // Execute delegate
                        Messenger.Default.Send("Hello!");
                    }
                )
            );
        }
    }

    #endregion

    public override void Cleanup() {
        // Clean up if needed

        base.Cleanup();
    }
}
    public SecondViewModel() {
        Messenger.Default.Register<string>(this, (s) => this.DoSomething(s));

        if (IsInDesignMode) {
            // Code runs in Blend --> create design time data.
        } else {
            // Code runs "for real": Connect to service, etc...
        }
    }

    #region [Message]

    public const string MessagePropertyName = "Message";

    private string _message = default(string);

    public string Message {
        get {
            return _message;
        }

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

            _message = value;

            RaisePropertyChanged(MessagePropertyName);
        }
    }

    #endregion

    public void DoSomething(string s) {
        this.Message = s;
    }

    public override void Cleanup() {
        base.Cleanup();
    }

}
SecondViewModel

 private void openNewSpecialCustomer()
    {
        GalaSoft.MvvmLight.Messaging.Messenger.Default.Send("Musaab");
        Console.WriteLine("send done");
        AddNewSpecialCustomer a = new AddNewSpecialCustomer();
        _dialogService.showDialoge(a);
    }
public AddNewSpecialCustomerViewModel()
    {
        GalaSoft.MvvmLight.Messaging.Messenger.Default.Register<string>(this,  doSomething);
        Console.WriteLine("Should now Receive");
        validProperties = new Dictionary<string, bool>();
        validProperties.Add("specialCustomerName",false);
        validProperties.Add("tel", false);
        allPropertiesValid = false;

    }

    public void doSomething(string s)
    {
        Console.WriteLine("Should be received");
        specialCustomerName = s;
        Console.WriteLine("s value " + s);
    }

    public String specialCustomerName
    {
        get { return _specialCustomerName; }
        set
        {
            if (_specialCustomerName != value)
            {
                _specialCustomerName = value;
               OnPropertyChanged("specialCustomerName");

            }
        }
    }
public class MainViewModel : ViewModelBase
{
    public MainViewModel() {
        if (IsInDesignMode) {
            // Code runs in Blend --> create design time data.
        } else {
            // Code runs "for real"
        }
        Messenger.Default.Send("Initializer - does not show becaus of race condition!");
    }

    public string Welcome {
        get {
            return "Welcome to MVVM Light";
        }
    }

    #region [TestCommand]

    private RelayCommand _cmdTest;

    public RelayCommand TestCommand {
        get {
            return _cmdTest ?? (
                _cmdTest = new RelayCommand(
                    () => {
                        // Execute delegate
                        Messenger.Default.Send("Hello!");
                    }
                )
            );
        }
    }

    #endregion

    public override void Cleanup() {
        // Clean up if needed

        base.Cleanup();
    }
}
    public SecondViewModel() {
        Messenger.Default.Register<string>(this, (s) => this.DoSomething(s));

        if (IsInDesignMode) {
            // Code runs in Blend --> create design time data.
        } else {
            // Code runs "for real": Connect to service, etc...
        }
    }

    #region [Message]

    public const string MessagePropertyName = "Message";

    private string _message = default(string);

    public string Message {
        get {
            return _message;
        }

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

            _message = value;

            RaisePropertyChanged(MessagePropertyName);
        }
    }

    #endregion

    public void DoSomething(string s) {
        this.Message = s;
    }

    public override void Cleanup() {
        base.Cleanup();
    }

}
public SecondViewModel(){
Messenger.Default.Register(this=>this.DoSomething);
如果(IsInDesignMode){
//代码在混合-->创建设计时数据中运行。
}否则{
//代码运行“真实”:连接到服务等。。。
}
}
#地区[讯息]
public const string MessagePropertyName=“Message”;
私有字符串_消息=默认值(字符串);
公共字符串消息{
得到{
返回消息;
}
设置{
如果(_message==值){
回来
}
_消息=值;
RaisePropertyChanged(MessagePropertyName);
}
}
#端区
公共无效剂量测定(字符串s){
this.Message=s;
}
公共覆盖无效清除(){
base.Cleanup();
}
}
主窗口XAML

<Window x:Class="MvvmLightTests.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        Height="300"
        Width="300"
        DataContext="{Binding Main, Source={StaticResource Locator}}">

    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Skins/MainSkin.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>

    <Grid x:Name="LayoutRoot">
        <StackPanel>
            <StackPanel>
                <TextBlock FontSize="36"
                       FontWeight="Bold"
                       Foreground="Purple"
                       Text="{Binding Welcome}"
                       VerticalAlignment="Center"
                       HorizontalAlignment="Center"
                       TextWrapping="Wrap" />
                <Button Content="click to send message" Margin="0,40,0,0" Command="{Binding TestCommand}" />
            </StackPanel>
            <StackPanel DataContext="{Binding SecondViewModel, Source={StaticResource Locator}}" Margin="0,40,0,0">
                <TextBlock Text="{Binding Message, TargetNullValue='--'}" FontWeight="Bold" HorizontalAlignment="Center"/>
            </StackPanel>
        </StackPanel>
    </Grid>
</Window>

由于消息的发送和接收都发生在构造函数中,因此可能会导致竞争条件。在构造函数中注册接收消息,但在稍后的时间点发送消息,例如在加载或命令处理程序中

编辑

public class ViewModelLocator
{
    private static MainViewModel _main;

    public ViewModelLocator() {
        CreateMain();
    }

    public static MainViewModel MainStatic {
        get {
            if (_main == null) {
                CreateMain();
            }

            return _main;
        }
    }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
        "CA1822:MarkMembersAsStatic",
        Justification = "This non-static member is needed for data binding purposes.")]
    public MainViewModel Main {
        get {
            return MainStatic;
        }
    }

    public static void ClearMain() {
        if (_main != null) {
            _main.Cleanup();
            _main = null;
        }
    }

    public static void CreateMain() {
        if (_main == null) {
            _main = new MainViewModel();
        }
    }

    #region [SecondViewModel]

    private static SecondViewModel _secondViewModel;

    public static SecondViewModel SecondViewModelStatic {
        get {
            if (_secondViewModel == null) {
                CreateSecondViewModel();
            }

            return _secondViewModel;
        }
    }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
        "CA1822:MarkMembersAsStatic",
        Justification = "This non-static member is needed for data binding purposes.")]
    public SecondViewModel SecondViewModel {
        get {
            return SecondViewModelStatic;
        }
    }

    public static void ClearSecondViewModel() {
        if (_secondViewModel != null) {
            _secondViewModel.Cleanup();
            _secondViewModel = null;
        }
    }

    public static void CreateSecondViewModel() {
        if (_secondViewModel == null) {
            _secondViewModel = new SecondViewModel();
        }
    }

    #endregion

    public static void Cleanup() {
        ClearMain();
        ClearSecondViewModel();
    }
}
无法重现该行为,以下是我用来测试该行为的代码:

视图定位器

public class ViewModelLocator
{
    private static MainViewModel _main;

    public ViewModelLocator() {
        CreateMain();
    }

    public static MainViewModel MainStatic {
        get {
            if (_main == null) {
                CreateMain();
            }

            return _main;
        }
    }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
        "CA1822:MarkMembersAsStatic",
        Justification = "This non-static member is needed for data binding purposes.")]
    public MainViewModel Main {
        get {
            return MainStatic;
        }
    }

    public static void ClearMain() {
        if (_main != null) {
            _main.Cleanup();
            _main = null;
        }
    }

    public static void CreateMain() {
        if (_main == null) {
            _main = new MainViewModel();
        }
    }

    #region [SecondViewModel]

    private static SecondViewModel _secondViewModel;

    public static SecondViewModel SecondViewModelStatic {
        get {
            if (_secondViewModel == null) {
                CreateSecondViewModel();
            }

            return _secondViewModel;
        }
    }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
        "CA1822:MarkMembersAsStatic",
        Justification = "This non-static member is needed for data binding purposes.")]
    public SecondViewModel SecondViewModel {
        get {
            return SecondViewModelStatic;
        }
    }

    public static void ClearSecondViewModel() {
        if (_secondViewModel != null) {
            _secondViewModel.Cleanup();
            _secondViewModel = null;
        }
    }

    public static void CreateSecondViewModel() {
        if (_secondViewModel == null) {
            _secondViewModel = new SecondViewModel();
        }
    }

    #endregion

    public static void Cleanup() {
        ClearMain();
        ClearSecondViewModel();
    }
}
MainViewModel

 private void openNewSpecialCustomer()
    {
        GalaSoft.MvvmLight.Messaging.Messenger.Default.Send("Musaab");
        Console.WriteLine("send done");
        AddNewSpecialCustomer a = new AddNewSpecialCustomer();
        _dialogService.showDialoge(a);
    }
public AddNewSpecialCustomerViewModel()
    {
        GalaSoft.MvvmLight.Messaging.Messenger.Default.Register<string>(this,  doSomething);
        Console.WriteLine("Should now Receive");
        validProperties = new Dictionary<string, bool>();
        validProperties.Add("specialCustomerName",false);
        validProperties.Add("tel", false);
        allPropertiesValid = false;

    }

    public void doSomething(string s)
    {
        Console.WriteLine("Should be received");
        specialCustomerName = s;
        Console.WriteLine("s value " + s);
    }

    public String specialCustomerName
    {
        get { return _specialCustomerName; }
        set
        {
            if (_specialCustomerName != value)
            {
                _specialCustomerName = value;
               OnPropertyChanged("specialCustomerName");

            }
        }
    }
public class MainViewModel : ViewModelBase
{
    public MainViewModel() {
        if (IsInDesignMode) {
            // Code runs in Blend --> create design time data.
        } else {
            // Code runs "for real"
        }
        Messenger.Default.Send("Initializer - does not show becaus of race condition!");
    }

    public string Welcome {
        get {
            return "Welcome to MVVM Light";
        }
    }

    #region [TestCommand]

    private RelayCommand _cmdTest;

    public RelayCommand TestCommand {
        get {
            return _cmdTest ?? (
                _cmdTest = new RelayCommand(
                    () => {
                        // Execute delegate
                        Messenger.Default.Send("Hello!");
                    }
                )
            );
        }
    }

    #endregion

    public override void Cleanup() {
        // Clean up if needed

        base.Cleanup();
    }
}
    public SecondViewModel() {
        Messenger.Default.Register<string>(this, (s) => this.DoSomething(s));

        if (IsInDesignMode) {
            // Code runs in Blend --> create design time data.
        } else {
            // Code runs "for real": Connect to service, etc...
        }
    }

    #region [Message]

    public const string MessagePropertyName = "Message";

    private string _message = default(string);

    public string Message {
        get {
            return _message;
        }

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

            _message = value;

            RaisePropertyChanged(MessagePropertyName);
        }
    }

    #endregion

    public void DoSomething(string s) {
        this.Message = s;
    }

    public override void Cleanup() {
        base.Cleanup();
    }

}
SecondViewModel

 private void openNewSpecialCustomer()
    {
        GalaSoft.MvvmLight.Messaging.Messenger.Default.Send("Musaab");
        Console.WriteLine("send done");
        AddNewSpecialCustomer a = new AddNewSpecialCustomer();
        _dialogService.showDialoge(a);
    }
public AddNewSpecialCustomerViewModel()
    {
        GalaSoft.MvvmLight.Messaging.Messenger.Default.Register<string>(this,  doSomething);
        Console.WriteLine("Should now Receive");
        validProperties = new Dictionary<string, bool>();
        validProperties.Add("specialCustomerName",false);
        validProperties.Add("tel", false);
        allPropertiesValid = false;

    }

    public void doSomething(string s)
    {
        Console.WriteLine("Should be received");
        specialCustomerName = s;
        Console.WriteLine("s value " + s);
    }

    public String specialCustomerName
    {
        get { return _specialCustomerName; }
        set
        {
            if (_specialCustomerName != value)
            {
                _specialCustomerName = value;
               OnPropertyChanged("specialCustomerName");

            }
        }
    }
public class MainViewModel : ViewModelBase
{
    public MainViewModel() {
        if (IsInDesignMode) {
            // Code runs in Blend --> create design time data.
        } else {
            // Code runs "for real"
        }
        Messenger.Default.Send("Initializer - does not show becaus of race condition!");
    }

    public string Welcome {
        get {
            return "Welcome to MVVM Light";
        }
    }

    #region [TestCommand]

    private RelayCommand _cmdTest;

    public RelayCommand TestCommand {
        get {
            return _cmdTest ?? (
                _cmdTest = new RelayCommand(
                    () => {
                        // Execute delegate
                        Messenger.Default.Send("Hello!");
                    }
                )
            );
        }
    }

    #endregion

    public override void Cleanup() {
        // Clean up if needed

        base.Cleanup();
    }
}
    public SecondViewModel() {
        Messenger.Default.Register<string>(this, (s) => this.DoSomething(s));

        if (IsInDesignMode) {
            // Code runs in Blend --> create design time data.
        } else {
            // Code runs "for real": Connect to service, etc...
        }
    }

    #region [Message]

    public const string MessagePropertyName = "Message";

    private string _message = default(string);

    public string Message {
        get {
            return _message;
        }

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

            _message = value;

            RaisePropertyChanged(MessagePropertyName);
        }
    }

    #endregion

    public void DoSomething(string s) {
        this.Message = s;
    }

    public override void Cleanup() {
        base.Cleanup();
    }

}
public SecondViewModel(){
Messenger.Default.Register(this=>this.DoSomething);
如果(IsInDesignMode){
//代码在混合-->创建设计时数据中运行。
}否则{
//代码运行“真实”:连接到服务等。。。
}
}
#地区[讯息]
public const string MessagePropertyName=“Message”;
私有字符串_消息=默认值(字符串);
公共字符串消息{
得到{
返回消息;
}
设置{
如果(_message==值){
回来
}
_消息=值;
RaisePropertyChanged(MessagePropertyName);
}
}
#端区
公共无效剂量测定(字符串s){
this.Message=s;
}
公共覆盖无效清除(){
base.Cleanup();
}
}
主窗口XAML

<Window x:Class="MvvmLightTests.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        Height="300"
        Width="300"
        DataContext="{Binding Main, Source={StaticResource Locator}}">

    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Skins/MainSkin.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>

    <Grid x:Name="LayoutRoot">
        <StackPanel>
            <StackPanel>
                <TextBlock FontSize="36"
                       FontWeight="Bold"
                       Foreground="Purple"
                       Text="{Binding Welcome}"
                       VerticalAlignment="Center"
                       HorizontalAlignment="Center"
                       TextWrapping="Wrap" />
                <Button Content="click to send message" Margin="0,40,0,0" Command="{Binding TestCommand}" />
            </StackPanel>
            <StackPanel DataContext="{Binding SecondViewModel, Source={StaticResource Locator}}" Margin="0,40,0,0">
                <TextBlock Text="{Binding Message, TargetNullValue='--'}" FontWeight="Bold" HorizontalAlignment="Center"/>
            </StackPanel>
        </StackPanel>
    </Grid>
</Window>

在第一个窗口构造函数之后是否调用了第二个窗口构造函数?
你应该先注册,然后再发送信息。未收到以前发送的消息。很抱歉成为C.O.但这种错误很可能发生:)

在第一个窗口构造函数之后是否调用了第二个窗口构造函数?
你应该先注册,然后再发送信息。未收到以前发送的消息。抱歉,作为C.O.但这种错误很可能发生:)

如果在剂量测定方法中发送断点,它是否会停止?您是否实现了IPropertyChanged接口?您的测试属性是否调用RaisePropertyChanged?我昨天用一个命令测试了它,它工作正常。我稍后发布测试。从编辑到原始发布,您可以看到我正在实现IPropertyChanged接口RaisePropertyChanged,我确实改变了onProperty,我相信他们也做了同样的事情,然后我把Console.WriteLine(“return”+test);'就在“test=s;”之后在doSomething()中,控制台上没有显示任何内容??问题变得更加奇怪了,我很好地运行了您的样本