这是我的视图模型:
class MainViewModel : ViewModelBase
{
private CalculatorViewModel calc;
public CalculatorViewModel Calculator {get {return calc; }set {calc = value; RaisePropertyChanged("Calculator");}}
}
class CalculatorViewModel : ViewModelBase
{
private CalculatorMode mode;
public CalculatorMode Mode {get {return mode;}set{mode=value; RaisePropertyChanged("CalculatorMode");}}
public CalculatorViewModel()
{
Mode = new HexMode();
}
}
abstract class CalculatorMode : ViewModelBase
{
abstract int Calculate(...);
}
class HexMode : CalculatorMode
{
public int Calculate(...) { ...}
}
这是我的 MainWindow(MainViewModel 实例设置为 Windows 的 DataContext):
<ad:DockingManager >
<ad:DockingManager.LayoutItemTemplateSelector>
<vm:PanesTemplateSelector>
<vm:PanesTemplateSelector.FileViewTemplate>
<DataTemplate>
<h:MyDocument />
</DataTemplate>
</vm:PanesTemplateSelector.FileViewTemplate>
<vm:PanesTemplateSelector.CalculatorViewTemplate>
<DataTemplate>
<w:Calculator />
</DataTemplate>
</vm:PanesTemplateSelector.CalculatorViewTemplate>
</vm:PanesTemplateSelector>
</ad:DockingManager.LayoutItemTemplateSelector>
</ad:DockingManager>
PanesTemplateSelector-Class 的代码:
public DataTemplate FileViewTemplate
{
get;
set;
}
public DataTemplate CalculatorViewTemplate
{
get;
set;
}
public override System.Windows.DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)
{
if (item is DocumentViewModel)
return FileViewTemplate;
if (item is CalcualtorViewModel)
return CalculatorViewTemplate;
return base.SelectTemplate(item, container);
}
计算器控件的内容:
<Grid Name="main">
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<ContentControl Name="content">
<ContentControl.ContentTemplateSelector>
<vm:CalculatorTemplateSelector>
<vm:CalculatorTemplateSelector.DefaultView>
<DataTemplate>
<TextBlock Text="Dummy for normal view" Foreground="Wheat" />
</DataTemplate>
</vm:CalculatorTemplateSelector.DefaultView>
<vm:CalculatorTemplateSelector.HexView>
<DataTemplate>
<TextBlock Text="Dummy für Hexview" Foreground="Gray"/>
</DataTemplate>
</vm:CalculatorTemplateSelector.HexView>
</vm:CalculatorTemplateSelector>
</ContentControl.ContentTemplateSelector>
</ContentControl>
</Grid>
CalculatorTemplateSelector-Class 的代码:
public DataTemplate HexView
{
get;
set;
}
public DataTemplate DefaultView
{
get;
set;
}
public override System.Windows.DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)
{
CalculatorViewModel cjmv = (CalculatorViewModel)item;
if (cjmv != null)
{
if (cjmv.Mode is HexMode)
return HexView;
return DefaultView;
}
return base.SelectTemplate(item, container);
}
第一个 TemplateSelector 正在工作。选择了正确的模板,我可以看到计算器控件。但是 Calculator-Control 中的 TemplateSelector 不起作用。在 CalculatorTemplateSelector.SelectTemplate 中,项目参数始终为空。但我需要 CalculatorViewModel 实例。我想我的问题是一个绑定问题,但我没有找到解决方案。有任何想法吗?