Uso el fragmento para Visual Studio, que genera propiedades con almacenamiento de respaldo y generación de eventos para mí. Simplemente crear el archivo XML con el nombre propchanged
(u otro nombre, si lo desea) y el siguiente contenido:
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>propchanged</Title>
<Shortcut>propchanged</Shortcut>
<Description>Code snippet for property (with call to OnPropertyChanged) and backing field</Description>
<Author>lazyberezovsky</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>type</ID>
<ToolTip>Property type</ToolTip>
<Default>string</Default>
</Literal>
<Literal>
<ID>property</ID>
<ToolTip>Property name</ToolTip>
<Default>MyProperty</Default>
</Literal>
<Literal>
<ID>field</ID>
<ToolTip>The variable backing this property</ToolTip>
<Default>myVar</Default>
</Literal>
</Declarations>
<Code Language="csharp">
<![CDATA[private $type$ $field$;
public $type$ $property$
{
get { return $field$;}
set
{
if ($field$ == value)
return;
$field$ = value;
OnPropertyChanged("$property$");
}
}
$end$]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
Y ponerlo a la carpeta C:\Users\YourName\Documents\Visual Studio 2010\Code Snippets\Visual C#\My Code Snippets\
.
A continuación, heredo mis ViewModels de algún ViewModelo base, que implementa la interfaz INotifyPropertyChanged
y proporciona el método protegido OnPropertyChanged
para generar el evento `PropertyChanged '.
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName);
}
}
Ahora cuando se escribe propchanged
en Visual Studio, se le preguntará por tipo de propiedad y el nombre, y generar código para usted.
public class PersonViewModel : ViewModel
{
// type here 'propchanged' (or other shortcut assigned for snippet)
}
ACTUALIZACIÓN:
Otra opción es la generación de código por el marco AOP como PostSharp. En este caso, el código se generará y agregará durante la compilación (por lo tanto, sus clases permanecerán limpias). Here es ejemplo de implementación INotifyProperty cambiar a través PostSharp atributos:
[Notify]
public class PersonViewModel
{
public Jurisdiction CountryResidence { get; set; }
public Jurisdiction CountryBirth { get; set; }
}
+1 por acuñar la frase "código repetitiva"! Voy a tener que usar ese. – Zannjaminderson
Si está utilizando C# 5, puede deshacerse de algún código repetitivo con nuevos atributos.Vea aquí: http://bhrnjica.net/2012/03/18/new-feature-in-c-5-0-callermembername/ – Vlad
@Vlad Gracias, esto parece limpio. En este caso, aunque todo C# 5 me da la capacidad de eliminar la cadena de 'OnPropertyChanged', ¿verdad? – Oliver