MvvmLight太多消息

时间:2015-07-26 20:05:13

标签: c# wpf mvvm

我正在切换两个视图。从Messenger.Default.Send<Message>(new Message {LoadingIndication="Loaded" },"Token");发送消息之后它正在回收两条消息,因为它在BinaryMultiViewModel中第一次创建OneViewModel两次,进入OneView。但我只需要一条消息。我无法删除某些东西,因为在第一种情况下它不应该在第二种情况下切换它应该显示数据。

例如

MultiView.cs

namespace Test.ViewModel
{
class BinaryMultiViewModel : ViewModelBase
{
    readonly static OneViewModel OneViewModel = new OneViewModel();

    readonly static FourViewModel FourViewModel = new FourViewModel();

    private ViewModelBase currentMultiViewModel;

    public BinaryMultiViewModel()
    {
        currentMultiViewModel = BinaryMultiViewModel.OneViewModel;
    }

    public ViewModelBase CurrentMultiViewModel
    {

        get
        {
            return currentMultiViewModel;
        }

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

            currentMultiViewModel = value;
            RaisePropertyChanged("CurrentMultiViewModel");
        }
    }
}
}

MultiView.xaml

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition></ColumnDefinition>
    </Grid.ColumnDefinitions>
    <ContentControl Grid.Column="0" Content="{Binding CurrentMultiViewModel}" />
</Grid>

OneViewModel.cs:

namespace Test.ViewModel
{
public class OneViewModel : ViewModelBase
{
    public OneViewModel()
    {
        Messenger.Default.Register<Message>(this,"Token", FromMultiModel);
    }
    private void FromMultiModel(Message input)
    {
        MessageBox.Show(input.LoadingIndication);
    }
}
}

OneView.cs

namespace Test.Views
{
public partial class OneView : UserControl
{
    public OneView()
    {
        DataContext = new OneViewModel();
        InitializeComponent();
    }
}
}

的App.xaml:

<DataTemplate DataType="{x:Type vm:OneViewModel}">
    <views:OneView/>
</DataTemplate>
<DataTemplate DataType="{x:Type vm:FourViewModel}">
    <views:FourView/>
</DataTemplate>

1 个答案:

答案 0 :(得分:0)

您无法在OneViewModel的ctor中创建OneView并将其分配给datacontext。

OneViewModel实例在BinaryMultiViewModel中创建,当您使用数据绑定将其设置为ContentControl时,选择带有OneView usercontrol的DataTempate,则OneViewModel为自动设置为OneView

的datacontext

只需删除第DataContext = new OneViewModel();行即可。