我只是想知道是否可以做这样的事情:
private int _x;
public int X
{
get{ return _x;}
set{_x = value; OnPropertyChanged(*theNameOfTheProperty*);}
}
没有实际指定OnPropertyChanged("X");
我想让OnPropertyChanged
更通用可能使用反射...
答案 0 :(得分:5)
有两种方法排序做你要问的事。第一个(仅限.NET 4.5+!)方法是将OnPropertyChanged修改为:
private void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
....
}
然后你从二传手中调用它:
set
{
_var = value;
OnPropertyChanged();
}
这会自动填充" propertyName"除非您明确提供参数,否则调用属性的参数。请注意,您需要using System.Runtime.CompilerServices;
来获取CallerMemberName
属性的命名空间。
另一种方法是编写propfull
代码段的自定义版本,以便在创建时为您填充。我的这个代码段的版本是:
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>propnp</Title>
<Shortcut>propnp</Shortcut>
<Description>Code snippet for property with OnPropertyChanged</Description>
<Author>Bradley</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>type</ID>
<ToolTip>Property type</ToolTip>
<Default>int</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[public $type$ $property$
{
get { return $field$;}
set
{
$field$ = value;
OnPropertyChanged($property$);
}
}
$end$]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
答案 1 :(得分:4)
您可以这样声明OnPropertyChanged
:
protected void OnPropertyChanged([CallerMemberName] string name = "")
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
然后你可以从属性中调用它:
public IEnumerable<Customer> Customers
{
get
{
return this.customers;
}
set
{
this.customers = value;
this.OnPropertyChanged();
}
}