开发者

MVVM Light Toolkit: Is it possible to Send a message in the xaml via a trigger?

Is it possible to Send a message i开发者_开发问答n the xaml via a trigger?

thanks.


I assume you're referring to MVVM Light Toolkit's messaging. If so, then No, this isn't possible.

However, it is not the responsibility of the View to do things like sending messages. The view's responsibility is to provide a view to the data and interaction with the user. Instead, you should have your ViewModel sending the message. You can "trigger" the message with a command in your view, but the command execute is what actually sends the message.

Here's an example View (MainPage.xaml) that has a couple of different ways to execute a command.

<UserControl x:Class="MvvmLight5.MainPage" 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:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.SL4" mc:Ignorable="d"
             DataContext="{Binding Main, Source={StaticResource Locator}}">
    <StackPanel x:Name="LayoutRoot">
        <TextBlock Text="Click Here to Send Message">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="MouseLeftButtonUp">
                    <cmd:EventToCommand Command="{Binding Path=SendMessageCommand, Mode=OneWay}"
                                        CommandParameter="Sent From TextBlock" />
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </TextBlock>
        <Button Content="Or Click Here"
                Command="{Binding Path=SendMessageCommand, Mode=OneWay}"
                CommandParameter="Sent From Button" />
    </StackPanel>
</UserControl>

And here's the MainViewModel.cs that sends the message.

using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;

namespace MvvmLight5.ViewModel
{
    public class MainViewModel : ViewModelBase
    {
        public RelayCommand<string> SendMessageCommand { get; private set; }

        public MainViewModel()
        {
            SendMessageCommand = new RelayCommand<string>(SendMessageCommandExecute);
        }

        private void SendMessageCommandExecute(string sentFrom)
        {
            Messenger.Default.Send(new NotificationMessage(sentFrom));
        }
    }
}

Also, I should note that these were created in Silverlight 4.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜