2010-11-30 77 views

回答

7

在Visual Studio 2010中获取设计时数据的一种简单方法是使用design-datacontext。使用Window和ViewModel的简短示例,对于DataContext,将在设计模式中使用d:DataContext,并在运行时使用StaticResource。您也可以使用单独的ViewModel进行设计,但在此示例中,我将对两者使用相同的ViewModel。

<Window ... 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     xmlns:local="clr-namespace:DesignTimeData" 
     mc:Ignorable="d"    
     d:DataContext="{d:DesignInstance local:MyViewModel, 
         IsDesignTimeCreatable=True}"> 
    <Window.Resources> 
     <local:MyViewModel x:Key="MyViewModel" /> 
    </Window.Resources> 
    <Window.DataContext> 
     <StaticResource ResourceKey="MyViewModel"/> 
    </Window.DataContext> 
    <StackPanel> 
     <TextBox Text="{Binding MyText}" 
       Width="75" 
       Height="25" 
       Margin="6"/> 
    </StackPanel> 
</Window> 

而在ViewModels属性MyText中,我们检查是否处于设计模式,在这种情况下,我们返回其他内容。

public class MyViewModel : INotifyPropertyChanged 
{ 
    public MyViewModel() 
    { 
     MyText = "Runtime-Text"; 
    } 

    private string m_myText; 
    public string MyText 
    { 
     get 
     { 
      // Or you can use 
      // DesignerProperties.GetIsInDesignMode(this) 
      if (Designer.IsDesignMode) 
      { 
       return "Design-Text"; 
      } 
      return m_myText; 
     } 
     set 
     { 
      m_myText = value; 
      OnPropertyChanged("MyText"); 
     } 
    } 
    public event PropertyChangedEventHandler PropertyChanged; 
    private void OnPropertyChanged(string propertyName) 
    { 
     if (PropertyChanged != null) 
     { 
      PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 
} 

Designer.cs,被发现here,看起来像这样

public static class Designer 
{ 
    private static readonly bool isDesignMode; 
    public static bool IsDesignMode 
    { 
     get { return isDesignMode; } 
    } 
    static Designer() 
    { 
     DependencyProperty prop = 
      DesignerProperties.IsInDesignModeProperty; 
     isDesignMode = 
      (bool)DependencyPropertyDescriptor. 
       FromProperty(prop, typeof(FrameworkElement)) 
         .Metadata.DefaultValue; 
    } 
} 
-3

您可以将您的内容包裹在另一个属性中,并测试该值是否为空。在这种情况下,返回你想要的假值。

private string _content; 
public string Content 
{ 
    get 
    { 
     if (_content != "") return _content; 
     else return "FAKE"; 
    } 
    set { _content= value; } 
} 
+0

在运行时不会这样做吗? – Jens 2010-11-30 13:57:00

3

可以使用FallbackValue属性显示在设计时的东西为好。但是,如果绑定失败,这也将是运行时的值。

<TextBox Text="{Binding MyText, FallbackValue='My Fallback Text'}"/>