2010-11-30 35 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'}"/>