我正在切换两个视图。从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>
答案 0 :(得分:0)
您无法在OneViewModel
的ctor中创建OneView
并将其分配给datacontext。
OneViewModel
实例在BinaryMultiViewModel
中创建,当您使用数据绑定将其设置为ContentControl
时,选择带有OneView
usercontrol的DataTempate,则OneViewModel
为自动设置为OneView
只需删除第DataContext = new OneViewModel();
行即可。