2012-08-04 2 views
0

개체의 형식을 가져 와서 개체로 동적으로 설정할 수 있습니까? 나는 모두가 같은 속성을 포함하고 내가 THEDYNAMICTYPE개체의 형식을 가져 와서 개체로 동적으로 설정하십시오.

어떤 제안으로 this.DataContext을 말하고 싶은 CamerasViewModel로 this.DataContext 말하는 대신이

if (this.DataContext is CamerasViewModel) 
{ 
    //Type type = Type.GetType((this.DataContext.ToString()); 
    object o = Assembly.GetExecutingAssembly().CreateInstance(this.DataContext.GetType().ToString()); 
    Type type = o.GetType(); 

    foreach (ButtonViewModel button in (this.DataContext as type).Buttons) 
    { 
     if (button.DisplayName == this.Content.ToString()) 
     { 
      this.Template = (ControlTemplate)this.FindResource(button.TemplateResource.Substring(0, button.TemplateResource.Length - 3) + "pr"); 
      break; 
     } 
    } 
} 

그런 짓을 할 몇 가지 ViewModels 있나요?

+0

아니요, 할 수 없습니다. 그리고 그렇게했다면 다음 단계는 무엇입니까? 또한 이미 정적 검사를 수행합니다. 나는 왜 당신이 그것에 문제가 있는지 알지 못한다. – leppie

+0

여기서 무엇을하려고합니까? 당신은 이미 this.DataContext가 첫 번째 "if"문으로 인해 CamerasViewModel이라는 것을 알고 있습니다. "Buttons"라는 ButtonViewModels 컬렉션이있는 모든 객체에서 button.DisplayName을 설정하려고합니까? –

+0

다른 모든 ViewModel 유형의 경우 문제는 tedius입니다. 그러나 귀하의 의견을 바탕으로, 불가능한 것 같습니다. Activator.CreateInstance로는 아무 것도 충분하지 않을까요? – bl4kh4k

답변

3

템플릿을 업데이트하고 인터페이스를 구현하려는 Buttons 속성을 가진 모든 클래스를 사용하는 것이 훨씬 나을 것입니다. 대신 객체가 CamerasViewModel 경우 검사, 당신의 if 문에,

public class CamerasViewModel : IHasButtons 
{ 
    public IEnumerable<ButtonViewModel> Buttons {get {. . .} set {. . .} } 
    . . . 
} 

다음 : 인터페이스는 다음과 같이 보일 것이다 :

public interface IHasButtons 
{ 
    public IEnumerable<ButtonViewModel> Buttons {get; set;} 
} 

및보기 모델은 다음과 같이 선언 될 것이다 그것이 IHasButtons인지 확인하십시오. 이 방법을 사용하면 객체에 Buttons 속성이 있는지 런타임에서 확인하는 것보다 훨씬 안전합니다. 운이 좋지 않아서 이름이 같지만 기대했던 것보다 다른 기능을 가진 Buttons 속성을 돌릴 수 있습니다. 그런 다음 여러분이 찾고있는 버튼 컬렉션이 진짜인지 결정하기 위해 미친 논리를 작성했습니다. 인터페이스를 사용하면 매우 명확합니다. ViewModel이 IHasButton을 구현하면 업데이트 할 ViewModel입니다. IHasButtons을 구현하지 않으면 바로 건너 뜁니다.

+0

훨씬 더 의미가 있습니다. 인터페이스를 구현하면 동적 인 유형이 실제로 무엇인지 가정하면 훨씬 안전 해집니다. 건배. – bl4kh4k

관련 문제