2012-12-10 59 views

回答

7

取决于。

我认为你的主要问题是ContentPresenter只在控制模板中使用。你不能把它粘在一个窗口中,并期望它显示窗口的内容。我相信你真的需要做的是使用ContentControl托管你的用户界面。

通过将模型绑定到此控件的Content属性,可以设置包含该模型的预期视图的DataTemplates。我会给你一个简短的例子。请注意,这可能与您的设计不符,但它展示了它们如何结合在一起。首先,对于每个视图,创建一个管理该视图的数据(和交互)的Model(或ViewModel)。

public sealed class Dialog : INotifyPropertyChanged // or DependencyObject 
{ 
    public string Input {get;set;} // INPC or DP implementation not shown 
    public ICommand Cancel {get;set;} 
    // class definition not shown 
} 

接下来,定义你的浏览在ContentPresenter显示

<UserControl x:Class="Herp.DialogView" 
    HideImplementationDetails="true"> 
    <Border BorderBrush="Red" BorderThickness="5"> 
     <TextBlock Text="{Binding Input}" /> 
     <Button Command="{Binding Cancel}">Cancel</Button> 
     <!-- etc etc -->  
    </Border> 
</UserControl> 

接下来,在你的窗口中添加ContentControl中和的DataTemplate

<Window HideImplementationDetailsForBrevityOfXaml="true"> 
    <Window.Resources> 
     <DataTemplate xmlns:t="clr-namespace:Herp" 
      DataType="{x:Type t:Dialog}"> 
      <t:DialogView /> 
     </DataTempalte> 
    </Window.Resources> 
    <ContentControl Content="{Binding}" /> 
</Window> 

最后设置的DataContext的窗口到您的Dialog模型。

public MyWindow() 
{ 
    InitializeComponent(); 
    DataContext = new Dialog(); 
} 

这是怎样的逻辑流程:创建

  1. 你的窗口。
  2. 对话框控件的一个实例在DataContext上设置。
  3. 在ContentControl中的绑定更新
  4. 默认的ContentControl搜索资源DataTemplateSelectorDataTemplateDataType设置为typeof(Dialog)
  5. 它发现窗口的资源在这个DataTemplate中
  6. 的DataTemplate中的内容是loaded并添加为的ContentControl

视觉孩子在任何时间的0 更改,重复相同的过程。因此,您可以拥有许多不同的模型,每个模型都包含一个不同的包含不同UserControl的DataTemplate,并且每次更新ContentControl上的绑定时都会看到期望的View。使用MVVM,您可以将ViewModel的属性绑定到Content属性(称为Current或某物),然后根据ViewModel的当前状态将属性中的模型切换为期望值。请注意,在ContentControl中,设置为Content属性的任何内容都将成为ContentControl的直接子节点的DataContext。类似于ItemsControl中的每个ItemsSourceItemTemplate中定义的可视树的DataContext

1

我隐藏了很多关于OK和Cancel的view-viewmodel交互方面的细节,但只要你有一个DataTemplate设置,那么这应该使你的视图在窗口内呈现。

我在我的应用程序的资源字典中定义我的视图模型视图的DataTemplates:

<DataTemplate DataType="{x:Type SaveDocumentChangesVM}"> 
    <SaveDocumentChangesView /> 
</DataTemplate> 

窗口以主视图:

<Window x:Class="CustomDialogWindow" 
     SizeToContent="WidthAndHeight" ShowInTaskbar="False"> 
    <ContentPresenter Name="DialogContentPresenter" /> 
</Window> 

的构造函数窗口:

public CustomDialogWindow(object viewModel, string dialogTitle) 
{ 
    InitializeComponent(); 

    // A datatemplate will allow WPF to figure out how to render the window contents 
    DialogContentPresenter.Content = viewModel; 

    if (dialogTitle != null) 
    { 
     Title = dialogTitle; 
    } 
} 

显示如下对话框:

var vm = new SaveDocumentChangesVM(); 
var dialog = new CustomDialogWindow(vm, "This is my dialog"); 
dialog.ShowDialog(); 
相关问题