확장 코드를 통해 코드에서 Application.Resources 요소를 검색하려고하는데 확장 메서드를 통해 그렇게하는 것이 효과적이지 않으므로 의아해합니다. , 반면에 똑같은 방법을 "정상적인"방법으로 성공시킨다.Silverlight 검색 4 확장 메서드를 통해 XAML에서 정의한 정적 리소스가 예상대로 작동하지 않습니다.
이 부분은 거의 독점적으로 Silverlight 개발의 자체 교육을 목표로합니다.
달성하려는 목표는 코드 숨김을 통해 XAML에서 TextBlock
일반 정보 (리소스로 정의 됨)를 검색하는 것입니다.
이
, 그것은 재산 "내 TextBlock에 흰색 페인트"는 간단 당신이 볼 수 있듯이<Application.Resources>
<Style x:Key="contentTextStyle" TargetType="TextBlock">
<Setter Property="Foreground" Value="White" />
</Style>
[...]
(이 App.xaml
내부에 정의되어) 재산입니다.
public static class ApplicationResources
{
public static void RetrieveStaticResourceExt<T>(this T obj, string resourceKey) where T : class
{
if(Application.Current.Resources.Contains(resourceKey))
obj = Application.Current.Resources[resourceKey] as T;
else
obj = null;
}
...
이 상기 방법 (이것은 참고하여 전화를 건 사람이다 :이 연장 방법의 형태로 코드
public static class ApplicationResources
{
public static T RetrieveStaticResource<T>(string resourceKey) where T : class
{
if(Application.Current.Resources.Contains(resourceKey))
return Application.Current.Resources[resourceKey] as T;
else
return null;
}
...
이다 : 여기
는 "정상"메소드의 클래스 다른 하지만 둘 다 같은 네임 스페이스)에 살고 :public static class UIElementsGenerator
{
/// <summary>
/// Appends a TextBlock to 'container', name and text can be provided (they should be, if this is used more than once...)
/// </summary>
public static void AddTextBlock(this StackPanel container, string controlName = "newTextBlock", string text = "")
{
TextBlock ret = new TextBlock();
ret.Text = controlName + ": " + text;
ret.TextWrapping = TextWrapping.Wrap;
//This uses the 1st non-extension method, this **WORKS** (textblock turns out white)
ret.Style = MyHelper.RetrieveStaticResource<Style>("contentTextStyle");
//This uses the 2nd one, and **DOESN'T WORK** (textbox stays black)
ret.Style.RetrieveStaticResourceExt<Style>("contentTextStyle");
container.Children.Add(ret);
}
...
코드는 그 자체로 설명이 간단 할 정도로 간단하다고 생각합니다.
확장 메소드 접근 방식의 문제점은 무엇입니까? Google과 SO 자체를 통해 브라우징, 그것은 내게 두 가지 방법으로 작동해야 보인다.
무엇이 누락 되었습니까?
Upvoted를 작동하기 때문에, 감사합니다. 어쨌든, 나는 어디에서나 속성의 이름을 전달할 수 있도록보다 일반적인 접근법을 따르고있다. (나는 controltemplates, 스타일 등을 생각하고있다.) 짧은 시간 안에 그 어떤 것도 나오지 않으면이 대답을 받아 들일 것입니다. – Alex
당신은 올바른 방법입니다 확장 메서드를 사용 하여이 개체를 바꿀 수 있습니다 알렉스. 부모 개체를 사용하여 확장 매개 변수를 적용하려면 하위 속성에 값을 할당하면됩니다. –