这可能是一个微不足道的问题,但找不到解决这个问题的好方法。我确实有一个在主视图中重复的用户控件(MyUserControl)。usercontrol 的一个实例呈现源对象,一个呈现目标对象。视图是相似的,但我需要知道用户控件的视图模型中哪个是源,哪个是目标。MainView 有 SourcenContent 和 TargetContent。所以问题是我如何在用户控件的视图模型中分离 SourcenContent 和 TargetContent?
主窗口`
<DockPanel LastChildFill="True">
<Border Height="400" DockPanel.Dock="Top">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="400"></RowDefinition>
<RowDefinition Height="50"></RowDefinition>
</Grid.RowDefinitions>
<GroupBox Header="Source Database" Grid.Row="0" Grid.Column="0">
<StackPanel Orientation="Vertical" >
<ContentControl Content="{Binding SourcenContent}" Name="source" VerticalAlignment="Stretch"/>
</StackPanel>
</GroupBox>
<GroupBox Header="Target Database" Grid.Row="0" Grid.Column="1">
<StackPanel Orientation="Vertical">
<ContentControl Content="{Binding TargetContent}" Name="Target" VerticalAlignment="Stretch"/>
</StackPanel>
</GroupBox>
</Grid>
</Border>
...
</DockPanel>
`
主视图模型
public class MainViewModel : ViewModelBase
{
private UserControl _sourcenContent;
private UserControl _targetContent;
private MyUserControl _sourcenContentUserControl;
private MyUserControl _targetContentUserControl;
public MainViewModel()
{
_sourcenContentUserControl = new MyUserControl();
_sourcenContent = _sourcenContentUserControl;
_targetContentUserControl = new MyUserControl();
_targetContent = _targetContentUserControl;
}
...
public UserControl SourcenContent
{
get { return _sourcenContent; }
set
{
if (_sourcenContent != value)
{
_sourcenContent = value;
RaisePropertyChanged("SourcenContent");
}
}
}
public UserControl TargetContent
{
get { return _targetContent; }
set
{
if (_targetContent != value)
{
_targetContent = value;
RaisePropertyChanged("TargetDatabaseConnectionContent");
}
视图模型定位器
public class ViewModelLocator
{
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
SimpleIoc.Default.Register<MainViewModel>();
SimpleIoc.Default.Register<MyUserControl>();
}
public MainViewModel MainViewModel
{
get
{
return ServiceLocator.Current.GetInstance<MainViewModel>();
}
}
public MyUserControlViewModel MyUserControlVM
{
get
{
return ServiceLocator.Current.GetInstance<MyUserControlViewModel>(Guid.NewGuid().ToString());
}
}
}
用户控制
<Grid Margin="8">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="75"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0" >
... Textboxes and other input controls
enter code here
MyUserControlViewModel
public class MyUserControlViewModel : ViewModelBase
{
public MyUserControlViewModel(IService service, ...)
{
**/* How do I know which user control created this SourcenContent or TargetContent*/**
}