CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    May 2001
    Location
    Silicon Valley
    Posts
    113

    Question Can’t seem to set the DataContext in XAML

    Colleagues,

    I’m experimenting with data binding. I wrote a simple test program with only one object representing a person and two TextBoxes bound to its properties (first and last names), which reside in the StackPanel layout. In the beginning, I was assigning the DataContext in the window’s constructor:
    Code:
    base.DataContext = m_objPerson;
    That worked.
    Then I’ve tried a different approach. Instead of assigning DataContext in code, I would like to assign it in XAML. StackPanel layout has a DataContext property. Shouldn’t it set the DataContext properties for all of the components contained in the layout? I’ve removed the assignment from code and added an assignment in XAML:
    Code:
    <StackPanel DataContext="m_objPerson">
    Unfortunately, the text boxes were no longer bound. Could anyone help me find the error?

    Cheer,
    -Nick

  2. #2
    Join Date
    Mar 2004
    Location
    Prague, Czech Republic, EU
    Posts
    1,701

    Re: Can’t seem to set the DataContext in XAML

    I think that to be able to set it this way, you need to have m_objPerson defined as "static resource". In debug, watch Output window, there I would expect error message like "m_objPerson is not defined".
    • Make it run.
    • Make it right.
    • Make it fast.

    Don't hesitate to rate my post.

  3. #3
    Join Date
    May 2001
    Location
    Silicon Valley
    Posts
    113

    Question Re: Can’t seem to set the DataContext in XAML

    Quote Originally Posted by boudino View Post
    I think that to be able to set it this way, you need to have m_objPerson defined as "static resource".
    Could you explain how to define the static resource? It probably should look like:
    Code:
        <Window.Resources>
            <!-- what goes here? -->
        </Window.Resources>
    But what goes in the middle?

    Quote Originally Posted by boudino View Post
    In debug, watch Output window, there I would expect error message like "m_objPerson is not defined".
    I'm not getting any messages in the output window (me at all).

  4. #4
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Can’t seem to set the DataContext in XAML

    Kender, rather than explaining here, I suggest you get a book on WPF. A book will be able to explain these WPF concept much better than what we could do in a forum.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured