Control Lifecycle

Programming/WPF 2015. 3. 11. 22:13
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

What happens when you create a Control? When do overrides get called and events get raised? When do styles get applied?


In response to this thread on silverlight.net, I've whipped this simple table up. There are some subtle differences between instantiating a control in XAML, and instantiating it via code that I've called out, but most of the lifecycle is the same.


ActionControl instantiated in XAMLControl instantiated in code
Control ctorAs soon as begin tag is parsed.When you call it.
Explicit Style appliedIf the Style property is set in XAML, it will be applied as soon as the end tag is parsed.As soon as Style property is set.
Built-in Style (from generic.xaml) appliedAs soon as the end tag is parsed, after the explicit Style (if any) has been applied. Will not override explicit Style.When the control enters the tree. Will not override explicit Style.
Properties setWhen the attributes are parsed.When you set them.
Loaded eventPosted when the element is been added to the tree. Fired before the next frame. Happens before layout.Same.
Template applied (i.e. control's visual are created from the Template)In the Measure pass of layout. The Template property will be applied if the control has no visual tree. The control starts life with no visual tree, and the visual tree will be cleared when the Template property is set. You can also call ApplyTemplate yourself.Same.
OnApplyTemplate calledWhenever the Template is applied. It is not necessary to call the base OnApplyTemplate for the Template to be applied, but inherited types might be relying on it for their implementations.Same.
Visuals first availableIn OnApplyTemplate. Use GetTemplateChild.Same.
MeasureOverride calledIn the Measure pass of layout. If the Template was expanded during this Measure pass, MeasureOverride will be called after the Template has been expanded.Same.
ArrangeOverride calledIn the Arrange pass of layout, which occurs after the Measure pass.Same.
SizeChanged eventAfter the Measure and Arrange passes have completed.Same.
LayoutUpdated eventAfter SizeChanged events have fired.Same.


출처 : http://blogs.msdn.com/b/devdave/archive/2008/10/11/control-lifecycle.aspx

Posted by 역시인생한방
,
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

 ContentControl은 아주 유용한 Control이면서 아주 기본적인 Control입니다. 우리가 알고 있는 대부분의 Control이 ContentControl을 상속받고 있죠. 일단 모든 Button류가 상속하고 있고 ListBoxItem등도 상속하고 있는 클래스입니다. 

   그럼 이것이 도데체 어떤 컨트롤인지 알아보기 위해 한번 화면에 뿌려보도록 하겠습니다. 

다음처럼 간단한 코드를 Xaml에 추가해보죠..

<ContentControl Content="This is a ContentControl!!"/>


화면에 단순히 "This is a ContentControl!!" 이라고 뿌려지는 것을 볼 수 있을 겁니다. 

뭐야... 그냥 TextBlock 인거야?... 하지만 다음과 같은 코드를 뿌려보면 단번에 뭐하는 녀석인지 알 수 있습니다. 

       <ContentControl>
            <ContentControl.Content>
                <Ellipse Width="50" Height="50" Fill="Purple"/>
            </ContentControl.Content>
        </ContentControl>


결과는 단순히 보라색 동그라미가 화면에 뿌려지는 것일 겁니다. (여기서 ContentControl.Content 태그는 생략해도 상관없습니다.)

아하 그러면 결국 이놈은 그냥 Content를 표시해주는 역활을 해주는 것이군요... 

사실 좀더 세부적으로 어떻게 구현되는 가를 살펴보기 위해 ContentControl의 Template을 살펴보도록 하죠. 

<ControlTemplate TargetType="ContentControl" >
    <ContentPresenter Content="{TemplateBinding Content}"  ContentTemplate="{TemplateBinding ContentTemplate}" Cursor="{TemplateBinding Cursor}" Margin="{TemplateBinding Padding}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
</ControlTemplate>


여러가지 속성들이 TemplateBinding 되어있는데 이런 속성들은 그냥 ContentControl의 속성을 ContentPresenter에 셋팅시켜주는 것일 뿐이고 결국은 내부적으로 ContentPresenter만 달랑 들어있는 형상이네요. 

  그럼 이 ContentPresenter 란 놈은 무슨 일을 하는지 알아봐야 겠죠. 아쉽게도 ContentPresenter는 Template도 없고 더 뜯어볼 코드도 없습니다. 

  예전 beta1때 공개되었던 코드를 참고하자면 다음과 같습니다. (현재의 CotentPresenter와 다른 점이 있을 수 있습니다. 일단 Text관련 Property들이 대부분 사라졌습니다. 현재는 ContentPresenter에 Content와 ContentTemplate 두가지 속성만이 있습니다. )


  코드를 살펴보면 다음과 같은 DefaultTemplate을 가지고 있는 것을 알 수 있습니다. 

private const string ContentPresenterDefaultTemplate =
            "<ControlTemplate " +
              "xmlns=\"
http://schemas.microsoft.com/client/2007\" " + 
              "xmlns:x=\"
http://schemas.microsoft.com/winfx/2006/xaml\" " + 
              "xmlns:controls=\"clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls\" " +
              "TargetType=\"controls:ContentPresenter\">" + 
                "<Grid x:Name=\"RootElement\" " +
                  "Background=\"{TemplateBinding Background}\" " +
                  "Cursor=\"{TemplateBinding Cursor}\">" + 
                    "<TextBlock x:Name=\"TextElement\" " +
                      "FontFamily=\"{TemplateBinding FontFamily}\" " +
                      "FontSize=\"{TemplateBinding FontSize}\" " + 
                      "FontStretch=\"{TemplateBinding FontStretch}\" " + 
                      "FontStyle=\"{TemplateBinding FontStyle}\" " +
                      "FontWeight=\"{TemplateBinding FontWeight}\" " + 
                      "Foreground=\"{TemplateBinding Foreground}\" " +
                      "HorizontalAlignment=\"{TemplateBinding HorizontalContentAlignment}\" " +
                      "Padding=\"{TemplateBinding Padding}\" " + 
                      "TextAlignment=\"{TemplateBinding TextAlignment}\" " +
                      "TextDecorations=\"{TemplateBinding TextDecorations}\" " +
                      "TextWrapping=\"{TemplateBinding TextWrapping}\" " + 
                      "VerticalAlignment=\"{TemplateBinding VerticalContentAlignment}\" " + 
                      "Visibility=\"Collapsed\" />" +
                "</Grid>" + 
            "</ControlTemplate>";


  간단히 Grid 안에 TextBlock 하나 있는 그런 Template인 거죠. 

  내부적인 구현을 보면 Content와 ContentTemplate Property Change 시 마다 자신의 DataContext에 Content나 ContentTemplate을 엮어준 후 PrepareContentPresenter라는 메소드를 호출해줍니다. 여기서 PrepareContentPresenter 라는 메소드에서는 다음과 같은 작업을 수행합니다. 

  1. 먼저 Default Template을 통해 들어있던 객체를 Grid로부터 제거 합니다. 
  2. 그리고 새로 받은 Template이 있으면 Template을 Content에 UIElement가 있으면 Content를 엘리먼트에 집어넣어줍니다. 
  3. 새로 셋팅된 Template도 없고 Content가 UIElement도 아닌 경우 Default Template에 있던 TextBlock의 Text값에  Content를 ToString 해서 넣어줍니다.

결국 ContentPresenter는 단순한 PlaceHolder 역활을 해준다는 것입니다. 여기서 한가지 알아보지 않은 것이 ContentTemplate 인데 ContentPresenter에 새로운 Template을 넣어준다고 생각하면 쉬울 것같습니다. 다음과 같은 코드를 실행해 보죠.


        <ContentControl Content="This is a ContentControl!!!">
            <ContentControl.ContentTemplate>
                <DataTemplate>
                    <Grid>
                        <Ellipse Width="200" Height="50" Fill="LightSteelBlue"/>
                        <TextBlock Text="{Binding }" VerticalAlignment="Center" HorizontalAlignment="Center" />
                    </Grid>
                </DataTemplate>
            </ContentControl.ContentTemplate>
        </ContentControl>

결과는  
  요렇습니다. 
여기서 Text="{Binding }" 부분은 ContentControl의 DataContext 바로 Content를 Binding 하겠다는 뜻입니다. 
그러니까 "This is a ContentControl!!!" 요 문장을 Text에 바인딩한 것이죠. 

Content 값이 바뀜에 따라 글자가 얼마든지 바뀔 수 있습니다. 그러면 다음과 같은 시도를 해보면 어떨까요?

        <ContentControl x:Name="contentControl">
           <ContentControl.ContentTemplate>
               <DataTemplate>
                    <Grid>
                       <Ellipse Width="200" Height="50" Fill="LightSteelBlue"/>
                       <TextBlock Text="{Binding Tag}" />
                    </Grid>
                </DataTemplate>
            </ContentControl.ContentTemplate>
        </ContentControl>

그리고 비하인드 코드에 다음과 같은 코드를 추가 시킵니다. 

  public partial class Page : UserControl
  {
        public Page()
        {
            InitializeComponent();
            contentControl.Content = new TestData() { Tag = "This is a ContentControl!!!" };
         }
   }

    public class TestData
   {
        public string Tag { get; set; }
   }

결과는 바로위의 예제와 같습니다. 

이번에는 TextBlock의 Text가 ,Content로 엮인 TestData의 Tag Property와 Binding 이 된 것이죠.

그럼 ContentControl에 대해 이해가 잘 되셨는지 모르겠군요.^^ 

마지막으로 한가지 팁을 알려드리자면. ContentControl은 Grid 나 Popup 같이 DataContext를 줄 수 없는 객체에 바인딩을 하는 용도로도 쓸 수 있어요.   Popup 이나 Grid 등을 ContentControl로 감싸고 ContentControl에 DataContext 값을 주면 되죠.. 이런게 어디 쓸모 있을까 싶겠지만 나중에 복잡한 바인딩 모델을 쓰다보면 불가피하게 써야 하는 경우가 생기더군요. 

  그럼 모두 삽질 덜 하시길..~^^

                                                                                                                         - smile -

p.s. 샘플프로젝트를 첨부합니다. 


출처 : http://error1001.tistory.com/40

Posted by 역시인생한방
,
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

Text="{StringFormat={}{0\,11:'#'#\,#}}"


{0\,11} 

자릿수가 총 11자리가 된다는 거


'#'

샾 문자를 삽입


#\,# 

3자리 수 마다 콤마 찍힘


출처 : http://msdn.microsoft.com/en-us/library/0c899ak8.aspx

Posted by 역시인생한방
,
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

未处理 System.InvalidOperationException

  Message=无法关闭撤消单元,因为不存在已打开的单元。


  Source=PresentationFramework

  StackTrace:

       在 MS.Internal.Documents.UndoManager.Close(IParentUndoUnit unit, UndoCloseAction closeAction)

       在 System.Windows.Documents.ImmComposition.CloseCompositionUndoUnit(UndoCloseAction undoCloseAction, ITextPointer compositionEnd)

       在 System.Windows.Documents.ImmComposition.UpdateCompositionText(FrameworkTextComposition composition, Int32 resultLength, Boolean includeResultText, ITextPointer& start, ITextPointer& end)

       在 System.Windows.Documents.ImmComposition.RaiseTextInputStartEvent(FrameworkTextComposition composition, Int32 resultLength, String compositionString)

       在 System.Windows.Documents.ImmComposition.OnWmImeChar(IntPtr wParam, Boolean& handled)

       在 System.Windows.Documents.ImmComposition.ImmCompositionFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)

       在 System.Windows.Interop.HwndSource.PublicHooksFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)

       在 MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)

       在 MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)

       在 System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)

       在 MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)

       在 System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)

       在 MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)

       在 MS.Win32.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)

       在 MS.Win32.HwndSubclass.DefWndProcWrapper(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)

       在 MS.Win32.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)

       在 MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)

       在 MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)

       在 System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)

       在 System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)

       在 System.Windows.Application.RunDispatcher(Object ignore)

       在 System.Windows.Application.RunInternal(Window window)

       在 System.Windows.Application.Run(Window window)

       在 System.Windows.Application.Run()

       在 LiveChainCHIS_Client.App.Main() 位置 D:\项目\LiveChainCHIS-Client\LiveChainCHIS-Client\obj\x86\Debug\App.g.cs:行号 0

       在 System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)

       在 System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)

       在 Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()

       在 System.Threading.ThreadHelper.ThreadStart_Context(Object state)

       在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)

       在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)

       在 System.Threading.ThreadHelper.ThreadStart()

  InnerException: 


补充说明一下 ,这个错误只出现于 数据绑定后的TextBox控件上。



解决办法:  设置Textbox的UndoLimit 为0就ok。


중문 윈도우에서 중문 IME를 이용해 TextBox에 글자를 입력하려고 하면 발생하는 예외 처리 방법

위에 써있듯이 TextBox에 UndoLimit을 0으로 설정해주면 해결된다


출처 : http://www.cnblogs.com/muzizongheng/p/3169812.html

Posted by 역시인생한방
,
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

예전에, .NET 응용 프로그램에서 예외 처리를 하는 방법에 관해 정리해놓았지요. ^^

.NET 예외 처리 정리 
; http://www.sysnet.pe.kr/Default.aspx?mode=2&sub=0&detail=1&wid=316

WPF - 전역 예외 처리 
; http://www.sysnet.pe.kr/Default.aspx?mode=2&sub=0&detail=1&wid=614


WPF로 오면서는 유독 First-chance Exception을 구분하는 것이 더 중요해졌습니다. 일례로 아래와 같은 경우들이 모두 "First-chance exception"을 모르면 문제를 해결하는 데 헤멜수가 있습니다.

예외 처리를 방해하는 WPF Modal 대화창
; http://www.sysnet.pe.kr/Default.aspx?mode=2&sub=0&detail=1&wid=619

WPF - XamlParseException 대응 방법
; http://www.sysnet.pe.kr/Default.aspx?mode=2&sub=0&detail=1&wid=622


다시 한번 강조하지만, "First-chance Exception"에 대해서 아직도 모르시는 분들은 부디 이번 기회에 꼭 알고 넘어가시기 바랍니다.

First-Chance Exception
; http://www.sysnet.pe.kr/Default.aspx?mode=2&sub=0&detail=1&wid=510





WPF에서, 예외 처리에 관해 어려움을 겪는 경우가 하나 더 있는데요. 아래의 코드를 보면서 설명해 보겠습니다.

public partial class Window1 : Window, INotifyPropertyChanged
{
    string name2;
    public string Name2
    {
        get { return this.name2; }
        set 
        {
            this.name2 = value;
            OnPropertyChanged("Name2");
            throw new ApplicationException("TEST");
        }
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        this.Name2 = "TEST";
    }
}


보통 위와 같은 상황에서, Visual Studio는 아래와 같이 정상적으로 디버그 지점을 잘 잡아냅니다.

[그림 1: ApplicationException 예외]
not_catch_databind_exception_1.png

하지만, 명시적으로 사용한 this.Name2 = "TEST" 코드를 삭제하고, 대신에 Name2 속성을 데이터바인딩으로 연결하면,

<TextBox Height="30" Margin="16,40,124,0" 
         Text="{Binding Path=Name2}"
/>


이제는 더 이상 Visual Studio IDE에서 예외를 잡아내지 못합니다. 단지 "Output"창에 다음과 같은 식으로 오류 로그가 출력될 뿐입니다.

A first chance exception of type 'System.ApplicationException' occurred in WpfApplication1.exe
A first chance exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll
System.Windows.Data Error: 8 : Cannot save value from target back to source. BindingExpression:Path=Name2; DataItem='Window1' (Name=''); target element is 'TextBox' (Name='textBox1'); target property is 'Text' (type 'String') TargetInvocationException:'System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ApplicationException: TEST
   at WpfApplication1.Window1.set_Name2(String value) in D:\Settings\desktop\binding_exception\WpfApplication1\WpfApplication1\Window1.xaml.cs:line 31
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
   at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
   at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, Object[] index)
   at MS.Internal.Data.PropertyPathWorker.SetValue(Object item, Object value)
   at MS.Internal.Data.ClrBindingWorker.UpdateValue(Object value)
   at System.Windows.Data.BindingExpression.UpdateSource(Object value)'


개인적으로 아쉬운 부분이 바로 위와 같이 데이터 바인딩 구문에서 예외를 먹어버리는 현상입니다. 아쉽긴 해도, WPF의 Validation 정책을 아시는 분들은 이런 식의 동작이 "By design"이라고 수긍이 되는 면이 있습니다.

WPF Sample Series - Handling and Reporting WPF Data Binding Validation Errors and Exceptions
; http://karlshifflett.wordpress.com/2008/04/03/wpf-sample-series-handling-and-reporting-wpf-data-binding-validation-errors-and-exceptions/


그러하니, 유효성 검사에서 자연스럽게 처리될 예외이므로 응용 프로그램 종료로 이어지는 예외 상황을 만들지 않도록 데이터 바인딩 과정에서 try/catch로 예외를 미리 처리하게 된 것입니다. 재미있는 점이 있다면, 마이크로소프트는 DataBinding 에 오류가 발생하는 것을 알 수 있도록 그나마 세심하게 배려했다는 정도!

How can I debug WPF bindings?
; http://www.beacosta.com/blog/?p=52


위의 글에 보면, 데이터 바인딩 오류에 대해 "Trace"로 오류 로그를 남기는 방법과 PresentationTraceSources.TraceLevel 을 이용한 방법을 소개해 주고 있습니다.

그래도... 이런 거에 만족할 수는 없지요? ^^ 어떻게 해서든지 저는 공용 속성의 set 접근자에서 발생하는 오류를 잡아내야 겠습니다.




단서를 찾을 수 있는 곳은 Validation을 처리하는 코드일 것 같습니다.

WPF Sample Series - Handling and Reporting WPF Data Binding Validation Errors and Exceptions 글에 보면, ExceptionValidationErrorHandler 코드를 볼 수 있는데요.

void ExceptionValidationErrorHandler(object sender, RoutedEventArgs e)
{
    System.Windows.Controls.ValidationErrorEventArgs arg = e as System.Windows.Controls.ValidationErrorEventArgs;

    ;
}


해답은 바로 위의 arg 인자에서 제공되는 Error 속성에 있습니다. 보통 ExceptionValidationErrorHandler 가 실행되는 경우는 다음과 같은 2가지 경우입니다.

  • 위에서 설명한 데로 set 접근자에서 오류가 발생한 경우, 또는 타입이 달라서 예외가 발생한 경우
  • IDataErrorInfo 를 구현한 개체가 해당 속성의 값이 유효하지 않다고 하는 경우


이 2가지를 구분하려면 arg.Error.RuleInError의 타입으로 검사하면 됩니다.

  • (arg.Error.RuleInError is ExceptionValidationRule) == true: 첫번째 경우
  • (arg.Error.RuleInError is DataErrorValidationRule) == true: 두번째 경우


이런 것을 반영해 보면 다음과 같은 식으로 코드를 만들면 될 것 같습니다.

void ExceptionValidationErrorHandler(object sender, RoutedEventArgs e)
{
    System.Windows.Controls.ValidationErrorEventArgs arg = e as System.Windows.Controls.ValidationErrorEventArgs;

    if (arg.Error.Exception != null && arg.Error.RuleInError is ExceptionValidationRule)
    {
        if (arg.Error.Exception is System.FormatException)
        {
            // 대개의 경우 발생할 수 있는 ExceptionValidationRule
        }
        else
        {
            // 그 외의 예외는 의도적이지 않은 예외
            throw arg.Error.Exception.InnerException;
        }
    }
}


이렇게 되면, 타입이 일치하지 않아 발생하는 예외는 그대로 Validation 검사로 진행하도록 하고, 그 이외의 상황에서는 throw를 해서 개발자로 하여금 set접근자에서 예외가 발생했음을 알 수 있도록 해줍니다.




그나마 예외 상황을 잡아보긴 했지만 아직 해결되지 않은 문제가 있습니다. ExceptionValidationErrorHandler 단계에서는 스택이 이미 풀린 상태이기 때문에 정확히 오류가 발생하는 곳에 코드를 위치시킬 방법이 없습니다. 할 수 없이, 예외가 발생했다는 정도만을 정확하게 인식하고 "throw arg.Error.Exception.InnerException"에서 확인할 수 있는 예외를 디버그 예외 상자에 등록하거나, 아니면 여전히 Output창의 "First-chance Exception"을 확인해서 디버그 예외 상자에 등록해 두는 식으로 접근해야 합니다.

게다가... 또 한가지 아쉬운 것은.

Validation 처리 과정으로 넘어오지 않은 예외에 대해서는 여전히 잡을 방법이 없습니다. 예를 들어, 데이터바인딩에는 "Name2"라는 속성명인데, 실제로는 그러한 속성이 없는 경우에는 ExceptionValidationErrorHandler까지 진입하지도 않습니다. 어쩔 수 없이 "How can I debug WPF bindings?" 에서 설명한 방식으로 데이터바인딩 예외를 추적하는 방법을 따라야 합니다.

관련 예제 코드는 첨부 파일에 올려놓았습니다.


출처 : http://www.sysnet.pe.kr/Default.aspx?mode=2&sub=0&detail=1&pageno=0&wid=746&rssMode=1&wtype=0

Posted by 역시인생한방
,
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.
<TextBlock>
    <TextBlock.Text>    
        <MultiBinding StringFormat="{}{0} + {1}">
            <Binding Path="Name" />
            <Binding Path="ID" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>


출처 : http://stackoverflow.com/questions/2552853/how-to-bind-multiple-values-to-a-single-wpf-textblock

Posted by 역시인생한방
,
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

(1) Intro

 윈폼을 건드려본 사람은 Label 과 TextBox 컨트롤은 매우 친숙할 것이다. WPF 에서는 여기에 TextBlock 이라는 컨트롤이 추가되었는데, 무엇이 다른걸까? 우선 MSDN 에서 각각의 컨트롤을 어떻게 정의했는지 살펴보자.


(이들은 모두 System.Windows.Controls 네임스페이스에 정의되어 있다.)

 컨트롤 

정의

 Label

Represents the text label for a control and provides support for access keys. 

 TextBlock

Provides a lightweight control for displaying small amounts of flow content.

 TextBox

Represents a control that can be used to display or edit unformatted text. 


Label 은 Access Key 를 이용해 접근하는 것을 지원한다. TextBlock 은 간단한 Content 를 매우 가볍게 제공한다. TextBox 는 우리가 알던대로 텍스트의 편집 / 뷰어를 제공한다. 의미만 봐서는 Label 과 TextBlock 의 차이점을 잘 알지 못하겠다. 왜냐하면 우리가 지금까지 알고있던 Label 의 개념과 이번에 나온 TextBlock 의 개념이 크게 차이가 나지 않기 때문이다. 이들의 차이점은 기본 자식의 개념에서 확실히 드러난다.


(2) 차이점

 Content Property 의 리턴타입은 object 형으로 거의 모든(Window를 제외하므로) 컨트롤을 지정할 수 있다. 여기서 Label 과 TextBlock 의 기본적인 차이가 드러난다.


 Label 과 TextBlock 과 TextBox 의 자식요소

 1. Label 의 기본 자식은 Content(object) 이다.

 2. TextBlock 의 기본 자식은 Text(string) 이다.

 3. TextBox 의 기본 자식은 Text(string) 이다.


 그렇다. Label 의 자식은 Content 로서, string 을 포함한 그 어떤 Control 이라도 지정할 수 있다. 하지만 TextBlock 의 자식은 string 밖에 되지 않는다. 기본 설계부터가 다른 것이다. 마음만 먹는다면 Label 의 Content 로 Button 을 지정할 수도 있다. 물론 Text 를 기본 자식으로 갖는 TextBlock 에서는 꿈도 꾸지 못할 일이다. Label 과 TextBlock 을 분류하자면 사용 용도에 따른 분류가 될 것이다.


 사용 용도에 따른 Label 과 TextBlock 의 분류

 * Text 만을 사용할 것이라면 TextBlock 을 쓰는 쪽이 가볍고 빠르다.

 * Text 외의 것까지 사용하고 싶다면 Label 을 사용하자(추후에 변화를 주고 싶다면)


출처 : http://blog.naver.com/PostView.nhn?blogId=inasie&logNo=70025582628&viewDate=%C2%A4tPage=1&listtype=0

Posted by 역시인생한방
,
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

https://msdn.microsoft.com/ko-kr/magazine/dd419663.aspx

Posted by 역시인생한방
,
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

Win32 API나 윈폼에서 한글 입력을 막기 위해 IME 관련 메시지들을 처리했던 기억이 있습니다. WPF와 Silverlight에서는 InputMethod 클래스의 SetIsInputMethodEnabled 메서드를 사용해서 쉽게 처리할 수 있습니다.

 

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBox x:Name="myTextBox1" HorizontalAlignment="Left" Height="23" Margin="10,10,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
        <TextBox x:Name="myTextBox2" HorizontalAlignment="Left" Height="23" Margin="10,38,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
    </Grid>
</Window>

 

using System.Windows;
using System.Windows.Input;

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            InputMethod.SetIsInputMethodEnabled(this.myTextBox1, false);
        }
    }
}

 

 
이외에도 InputMethod 클래스는 IME와 관련된 많은 기능을 제공합니다.


출처 : http://styletigger.tistory.com/entry/WPF%EC%99%80-Silverlight%EC%97%90%EC%84%9C-TextBox%EC%9D%98-%ED%95%9C%EA%B8%80-%EC%9E%85%EB%A0%A5%EC%9D%84-%EB%A7%89%EB%8A%94-%EB%B0%A9%EB%B2%95

Posted by 역시인생한방
,
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

WPF에서는 메인스레드에서 생성한 컨트롤에 다른 스레드가 접근하지 못하도록 되어있습니다.

 

접근하려고 하면 다음과 같은 에러메시지에 직면하죠 :

다른 스레드가 이 개체를 소유하고 있어 호출한 스레드가 해당 개체에 액세스할 수 없습니다.”

 

Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate

{

    lblStatus.Content = "동작중"; // 해당 소스

}));

 

다음과 같이 메인 Dispatcher를 통해 라벨내용을 변경시켜주시면 문제없이 돌아갑니다.


출처 : http://inasie.tistory.com/16

Posted by 역시인생한방
,