2011-11-16 14 views
15

Tôi có một lớp (điều khiển), triển khai ICustomTypeDescriptor, được sử dụng cả lúc thiết kế và thời gian chạy bởi PropertyGrid để tùy chỉnh. Tôi cần để lộ các thuộc tính khác nhau tại thời điểm thiết kế (các thuộc tính điều khiển chuẩn như width, height và vân vân) và tại thời gian chạy, khi PropertyGrid được sử dụng trong chương trình của tôi để thay đổi các thuộc tính khác của điều khiển đó.Làm thế nào để biết liệu một điều khiển có ở thời gian thiết kế hay không?

Mã của tôi cũng giống như:

class MyControl : UserControl, ICustomTypeDescriptor 
{ 
    //Some code.. 

    public PropertyDescriptorCollection GetProperties(Attribute[] attributes) 
    { 
     return GetProperties(); 
    } 

    public PropertyDescriptorCollection GetProperties() 
    { 
     //I need to do something like this: 
     if (designTime) 
     { //Expose standart controls properties 
      return TypeDescriptor.GetProperties(this, true); 
     } 
     else 
     { 
      //Forming a custom property descriptor collection 
      PropertyDescriptorCollection pdc = new PropertyDescriptorCollection(null); 
      //Some code.. 
      return pdc; 
     } 
    } 
} 

Có một analog cho một lá cờ thiết kế thời gian trong C#? Có thể sử dụng trình biên dịch có điều kiện tốt hơn không?

+1

Bạn đang nói về wpf hoặc winform? –

+0

Bản sao có thể có của * [Cách để biết liệu mã .NET có đang được chạy bởi nhà thiết kế Visual Studio] hay không (http://stackoverflow.com/questions/73515/how-to-tell-if-net-code-is-being- run-by-visual-studio-designer) *. –

Trả lời

10

Kiểm tra xem DesignMode có đúng hay sai. Đó là một thuộc tính thuộc về lớp cơ sở điều khiển.

+2

Thực ra, nó thuộc về lớp cơ sở 'System.ComponentModel.Component'. – tafa

8

Cờ phải là DesignMode. Do đó mã của bạn nên trông giống như sau

public PropertyDescriptorCollection GetProperties() 
{ 
    //I need to do something like this: 
    if (this.DesignMode) 
    { //Expose standart controls properties 
     return TypeDescriptor.GetProperties(this, true); 
    } 
    else 
    { //Forming a custom property descriptor collection 
     PropertyDescriptorCollection pdc = new PropertyDescriptorCollection(null); 
     //Some code.. 
     return pdc;  
    } 
} 

Đây là theo MSDN doc.

3

Sử dụng thuộc tính DesignMode của cơ sở. Điều này sẽ cho bạn biết về chế độ này.