在我的MVVM應用程序中,我有一個樹形視圖來表示數據庫中的記錄。我的意見,並在的ViewModels資源字典鏈接這樣wpf用戶控件模板
<DataTemplate DataType="{x:Type vm:TrialSiteViewModel}">
<vw:TrialSiteView />
</DataTemplate>
我想,當用戶使用工具提示懸停在圖標顯示視圖的預覽。我在TreeView HierarchicalDataTemplate是這個
<HierarchicalDataTemplate DataType="{x:Type vm:TrialSiteViewModel}"
ItemsSource="{Binding Path=Children}">
...
<Button Style="{StaticResource previewButtonStyle}">
<Button.ToolTip>
<ToolTip Style="{x:Null}">
<ToolTip.ContentTemplate>
<DataTemplate>
<localtools:ObjectPreview
PreviewObject="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type TreeViewItem}}, Path=DataContext}"
/>
</DataTemplate>
</ToolTip.ContentTemplate>
</ToolTip>
</Button.ToolTip>
</Button>
</StackPanel>
</HierarchicalDataTemplate>
這正確拿起TrialSiteViewModel是在DataContext的樹型視圖。
ObjectPreview使用視框和ContentControl中顯示的記錄的視圖
<Viewbox Grid.Row="1" Name="treeviewViewBox"
Stretch="Uniform"
IsEnabled="False">
<ContentControl Name="treeViewItemViewModel"
Content="{Binding PreviewObject}">
</ContentControl>
</Viewbox>
和後面的代碼包含依賴屬性
public partial class ObjectPreview : UserControl
{
public ObjectPreview()
{
InitializeComponent();
}
public static readonly DependencyProperty _previewObjectProperty =
DependencyProperty.Register("PreviewObject", typeof(TreeViewItemViewModel), typeof(ObjectPreview));
public TreeViewItemViewModel PreviewObject
{
get { return (TreeViewItemViewModel)GetValue(_previewObjectProperty); }
set { SetValue(_previewObjectProperty, value); }
}
}
時遇到的問題是,所使用的模板顯示對象與樹視圖中使用的相同。這只是顯示一個圖標和一個對象摘要(即主鍵和一個或兩個關鍵字段),而不是視圖TrialSiteView中定義的整個模板。如果我修改代碼以使用TrialSiteViewModel上的按鈕Command並將其注入到ObjectPreview中,我可以在後面的代碼中設置contentcontrol,並使用TrialSiteView。
我猜,以某種方式模板是從TreeViewItem推斷。任何人都可以告訴我如何確保工具提示使用TrialSiteView?
UPDATE
好了,我已經解決了這個問題,但不得不求助於後面的代碼,並刪除該用戶控件,並直接把視圖的提示。關鍵是從資源獲取數據模板。我之前曾試圖通過將鍵分配給數據模板來完成此操作,但是我的代碼有缺陷或無法使用。無論如何,這可行,但不是首選的Xaml解決方案。
private void PreviewObject_MouseEnter(object sender, MouseEventArgs e)
{
Image image = (Image)sender;
var key = new System.Windows.DataTemplateKey(image.DataContext.GetType());
var datatemplate = (DataTemplate)this.FindResource(key);
ToolTip tooltip = new ToolTip();
tooltip.Style = VisualUtils.GetResource<Style>("ControlTemplates.xaml", "toolTipWithContentStyle");
tooltip.MaxWidth = 460;
ContentControl contentcontrol = new ContentControl();
contentcontrol.ContentTemplate = datatemplate;
contentcontrol.Content = image.DataContext as TreeViewItemViewModel;
Viewbox viewbox = new Viewbox();
viewbox.Stretch = Stretch.Uniform;
viewbox.Child = contentcontrol;
tooltip.Content = viewbox;
image.ToolTip = tooltip;
}
你只有onee您的視圖模型的DataTemplate,所以它將被應用於每個內容的控制。如果你想使用不同的模板 - 明確應用它。 – vorrtex 2011-05-09 13:22:13