Source 먼저 x:Name 어트리뷰트가 "Output"으로 설정된 TextBlock만을 가진 MyUserControl이라는 유저 컨트롤의 코드 비하인드에 다음의 코드를 입력하고 다른 유저 컨트롤(Page)에 MyUserControl을 추가 했어요.
using System; using System.Windows.Controls; using System.IO.IsolatedStorage; namespace IsolatedStorageCrashInBlend { public partial class MyUserControl : UserControl { public MyUserControl() { InitializeComponent(); // 디자인 모드가 아닐 경우에만 처리 // 설정을 읽어 Output에 출력 if (IsolatedStorageSettings.ApplicationSettings.Contains("LastGuid")) { Output.Text = IsolatedStorageSettings.ApplicationSettings["LastGuid"].ToString(); } else { // 설정이 없으면 새 값을 저장 IsolatedStorageSettings.ApplicationSettings["LastGuid"] = Guid.NewGuid().ToString(); } } } }
Incorrect IsolatedStorage와 관련된 코드를 포함하는 컨트롤 자체는 블렌드에서 디자인이 잘 보여요. 이유는 이 전에 포스팅 했고요.
Correct 그러나 IsolatedStorage와 관련된 코드를 포함하는 컨트롤을 다른 컨트롤의 XAML에서 추가했을 때 블렌드에서 디자인이 안보이면서 복장터지는 에러 메시지만 내뿜죠.
Solution 이 문제는 이 전 포스팅에서 얘기했듯이 DesignerProperties를 사용하여 피해갈 수 있어요.
using System; using System.Windows.Controls; using System.IO.IsolatedStorage; using System.ComponentModel; namespace IsolatedStorageCrashInBlend { public partial class MyUserControl : UserControl { public MyUserControl() { InitializeComponent(); // 디자인 모드일 때에는 임의의 값 출력 if (DesignerProperties.GetIsInDesignMode(this) == true) { Output.Text = Guid.NewGuid().ToString(); } else { // 디자인 모드가 아닐 경우에만 처리 // 설정을 읽어 Output에 출력 if (IsolatedStorageSettings.ApplicationSettings.Contains("LastGuid")) { Output.Text = IsolatedStorageSettings.ApplicationSettings["LastGuid"].ToString(); } else { // 설정이 없으면 새 값을 저장 IsolatedStorageSettings.ApplicationSettings["LastGuid"] = Guid.NewGuid().ToString(); } } } } }
잘 나오죠? 하지만 위의 코드는 좋은 패턴이 아니에요. 약간만 리팩터링을 해보죠.
using System; using System.Windows.Controls; using System.IO.IsolatedStorage; using System.ComponentModel; namespace IsolatedStorageCrashInBlend { public partial class MyUserControl : UserControl { public MyUserControl() { InitializeComponent(); // 디자인 모드일 때에는 임의의 값 출력 if (DesignerProperties.GetIsInDesignMode(this) == true) { Output.Text = Guid.NewGuid().ToString(); } else { // 디자인 모드가 아닐 경우에만 처리 InitializeApplicationData(); } } private void InitializeApplicationData() { // 설정을 읽어 Output에 출력 if (IsolatedStorageSettings.ApplicationSettings.Contains("LastGuid")) { Output.Text = IsolatedStorageSettings.ApplicationSettings["LastGuid"].ToString(); } else { // 설정이 없으면 새 값을 저장 IsolatedStorageSettings.ApplicationSettings["LastGuid"] = Guid.NewGuid().ToString(); } } } }
네, 다른 모든 코드도 마찬가지지만 특히 IsolatedStorage와 관련된 코드는 별도의 코드 블럭으로 빼주는 것이 좋아요.
아니, 반드시 그렇게 해야 해요.
이 외에도 블렌드에서만 발생하는 문제가 가끔 있는데요, 그 문제가 코드와 연관된 것이라면 DesiginerProperties를 사용하여 회피할 수 있어요.
샘플을 첨부했으니 한 번 이렇게 저렇게 테스트 해 보세요.