2011-12-13 27 views
1

我正在用C#編寫一個使用數據綁定的winforms應用程序。最近我發現我寫了很多屬性,如下面顯示的代碼。可以編寫這些代碼,但我在想也許我錯過了一些東西,也許我可以減少代碼並使代碼看起來更乾淨?有沒有辦法爲我的班級自動生成這些數據綁定就緒屬性?

有沒有自動化的方法呢?
像Codedom或任何框架,我不知道?

public class SampleClass : INotifyPropertyChanged 
{ 
    public Boolean Enabled 
    { 
     get { return _enabled; } 
     set 
     { 
      if (_enabled == value) return; 

      _enabled = value; 

      // broadcast the change 
      RaisePropertyChanged(PropertyName_Enabled); 

      // this object is modified 
      this.Modified = true; 
     } 
    } 

    public Single Degree 
    { 
     get { return _degree; } 
     set 
     { 
      if (_degree == value) return; 

      _degree = value; 

      // broadcast the change 
      RaisePropertyChanged(PropertyName_Degree); 

      // this object is modified 
      this.Modified = true; 
     } 
    } 

    // Define the property name this class exposes and notifies 
    public static readonly String PropertyName_Enabled = "Enabled"; 
    public static readonly String PropertyName_Degree = "Degree"; 

    private Boolean _enabled; 
    private Single _degree;  
}  

回答

1

只需創建一個code snippet

<?xml version="1.0" encoding="utf-8"?> 
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"> 
    <CodeSnippet Format="1.0.0"> 
    <Header> 
     <SnippetTypes> 
     <SnippetType>Expansion</SnippetType> 
     </SnippetTypes> 
     <Title>propnot</Title> 
     <Author>Thomas Levesque</Author> 
     <Description>Code snippet for property with change notification</Description> 
     <HelpUrl> 
     </HelpUrl> 
     <Shortcut>propnot</Shortcut> 
    </Header> 
    <Snippet> 
     <Declarations> 
     <Literal Editable="true"> 
      <ID>type</ID> 
      <ToolTip>Property type</ToolTip> 
      <Default>int</Default> 
      <Function> 
      </Function> 
     </Literal> 
     <Literal Editable="true"> 
      <ID>property</ID> 
      <ToolTip>Property name</ToolTip> 
      <Default>MyProperty</Default> 
      <Function> 
      </Function> 
     </Literal> 
     <Literal Editable="true"> 
      <ID>field</ID> 
      <ToolTip>The variable backing this property</ToolTip> 
      <Default>myProperty</Default> 
      <Function> 
      </Function> 
     </Literal> 
     <Literal Editable="true"> 
      <ID>notifyMethod</ID> 
      <ToolTip>The method used to notify the listeners</ToolTip> 
      <Default>OnPropertyChanged</Default> 
      <Function> 
      </Function> 
     </Literal> 
     </Declarations> 
     <Code Language="csharp"><![CDATA[private $type$ $field$; 
public $type$ $property$ 
{ 
    get { return $field$;} 
    set 
    { 
     $field$ = value; 
     $notifyMethod$("$property$"); 
    } 
} 
$end$]]></Code> 
    </Snippet> 
    </CodeSnippet> 
</CodeSnippets> 

(這是不完全一樣的,你所示的代碼,但是你可以很容易地適應您的需求)

不可否認的是,代碼不會看起來更乾淨,但至少你會花更少的時間來寫它;)

相關問題