2015-02-24 79 views
0

可能有人为这个答案提供简单的例子代码:One way to get feedback if your bindings are broken, is to create a DataTemplate and declare its DataType to be the type of the ViewModel that it binds toWPF DataTemplate的安全数据绑定

如何重构例如:

<UserControl x:Class="Application.Views.TestView" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      xmlns:vm="clr-namespace:Application.ViewModels" 
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300">   
     <Grid>  
      <StackPanel HorizontalAlignment="Left" Height="34" VerticalAlignment="Top"> 
       <Button Content="Press me!" Command="{Binding Path=ServiceReadCommand}" /> 
       <ListBox Width="200" Height="200" DataContext="{Binding ReactiveList}" /> 
      </StackPanel> 
     </Grid>   
</UserControl> 

控制,然后在ReactiveUi用作:

// Navigate to the opening page of the application 
Router.Navigate.Execute(new TestViewModel(this)); 
AppBootStrapper中的

回答

0

回答指的是被称为隐式数据模板。这是一个DataTemplate,它包含一个数据类型,但没有关键属性来标识它。

每当WPF在Visual树中绘制一个非UI对象时,它会检查是否有任何模板已经为该对象首先定义。

举例来说,如果你有你的<XXXX.Resources>以下地方

<DataTemplate DataType="{x:Type local:TestViewModel}"> 
    <local:TestView /> 
</DataTemplate> 

然后随时随地WPF试图绘制TestViewModel对象在UI,它会使用TestView绘制。

ContentControl一个经常用于插入代码对象在UI因为.Content属性可以是任何对象,包括的ViewModels或模型。

<ContentControl Content="{Binding CurrentViewModel}" /> 

您链接的问题是关于如何使绑定本身类型安全并支持重构,而这不会做到这一点。例如,如果您有<TextBox Text="{Binding Name}" />并且您想要将Name重命名为GroupName,Visual Studio将不知道.Name属性已链接到重命名的.GroupName属性。

+0

如果我把''放入''DataTemplate DataType =“{x:Type vm:TestViewModel}”>'那么我可以使用Resharper重构。 Q是如何用该“模板”替换UserControl以及如何使用它。如果我把''放入''反应式绑定不起作用。 – Tomasito 2015-02-24 16:48:24

+0

我没有使用Resharper重构,所以不能帮助你。在这种情况下,你可以保留你的'UserControl'并且让DataTemplate使用UserControl'TestView'来绘制任何'TestViewModel'对象,就像我在代码示例中一样,或者你可以复制/粘贴UserControl的内容在'')到DataTemplate中。 DataTemplates通常在''中定义,但如果您只希望它们适用于较小的作用域,例如'',则可以将它们向下移动, – Rachel 2015-02-24 16:52:01