1. 事件订阅
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
Application.Current.MainWindow.SizeChanged += MainWindow_SizeChanged;
}
private void MainWindow_SizeChanged(object sender, SizeChangedEventArgs e)
{
// Handle size changed event
}
}
2. 匿名函数中捕获对象成员
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
Application.Current.MainWindow.SizeChanged += (s, e) => {
Debug.WriteLine($"{e.NewSize.Width - this.Width}");
};
}
}
3. 静态变量
public class MyClass
{
static List<MyClass> _instances = new List<MyClass>();
public MyClass()
{
_instances.Add(this);
}
}
4. 非托管资源
public class SomeClass
{
private IntPtr _buffer;
public SomeClass()
{
_buffer = Marshal.AllocHGlobal(1000);
}
~SomeClass()
{
Marshal.FreeHGlobal(_buffer);
}
}
5. WPF绑定
public class MyViewModel : INotifyPropertyChanged
{
private string _someText;
public string SomeText
{
get { return _someText; }
set
{
_someText = value;
OnPropertyChanged(nameof(SomeText));
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
总结
往期精品推荐: