3

Is it possible to send a List in MVVM Light Message.

For example, I have a class named Authors. I want to send

Messenger.Default.Send(AuthorList); // AuthorList is of type List<Author>

in the constructor of the view model I am writing

Messenger.Default.Register<List<Author>>(this, authList => 
    {MessageBox.Show(authList[0].name)});

I have made sure that the constructor is called before I send the message. But it doesn't seem to work.


Centering Multiple Items

In my app, I have a bunch of rectangles.

enter image description here

I am trying to horizontally centerize all of these rectangles on the screen. (The center is screen_width/2)

Here is my code so far (for your viewing pleasure),

            for (var j=0;j<rectangles.length;j++){
                rectangle=rectangles[j];
                                    var margin=120;
                var coefficent=0;
                var center_index=Math.ceil(rectangles.length/2);
                if (j>center_index){
                     coefficent=1;
                }else if (j<center_index){
                    coefficent=-1;
                }


                var x=(screen.width-rectangle.width)/2+j*margin*coefficent;
                rectangle.SetX(x);

                }

This code puts everything in the center (not cool).

Any help on this problem would be splendidly appreciated.

Edit:

Sorry for not being clear,

Heres another image to be more clear (the line, is the center line):

enter image description here

So you can see, that we are shifting all the rectangles so that the middle rectangle is in the center.

Like when you press the center button to centerize text horizontally on a Word Document, I am trying to do this with rectangles.

4

1 回答 1

3

是的 。创建你的类(我正在使用其中有一个简单字符串属性的 MyTest):

public partial class MyTest
{
    public MyTest(string some_string)
    {
        S = some_string;
    }

    public string S { get; set; }
}

您可以从任何地方调用它,在 ViewModel 中,我添加了一个按钮,该按钮将创建该列表并将其发送到不同的视图。:

private void Button_Click(object sender, RoutedEventArgs e)
    {
        var list_of_objects = new List<MyTest> { new MyTest("one"), new MyTest("two") };
        Messenger.Default.Send(list_of_objects );
    }

在接收 ViewModel 上,在构造函数中添加这个以注册到该类型的消息,并创建一个将在消息到达时调用的方法:

// When a message with a list of MyTest is received
// this will call the ReceiveMessage method  :  
Messenger.Default.Register<List<MyTest>>(this, ReceiveMessage);

实现回调方法:

private void ReceiveMessage(List<MyTest> list_of_objects)
    {
        // Do something with them ... i'm printing them for example         
        list_of_objects.ForEach(obj => Console.Out.WriteLine(obj.S));
    }

你完成了 :)

于 2013-09-27T07:31:11.940 回答