CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Jun 2010
    Posts
    7

    Binding to object in code behind

    In Window1.xaml.cs I have an object how can I bind to it's properties?
    Code:
    private RamManager ramManager;
    
    public Window1()
    {
          ramManager = new RamManager();
          ramManager.StartThread();
    
          InitializeComponent();
    }
    what I need is in Window1.xaml
    Code:
    <ProgressBar Name="ramBar" Maximum="{Binding Path=ramManager.TotalRam}" Value="{Binding Path=ramManager.AvailableRam}" />
    Thank you in advance

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

    Re: Binding to object in code behind

    First of all, since the RamManager is multithreaded, you'll need to make it's public properties threadsafe.

    Next, you need to implement the INotifyPropertyChanged interface in the RamManager.

    You also will need to change the bindings in xaml

    Code:
    <ProgressBar Name="ramBar" Maximum="{Binding Path=TotalRam}" Value="{Binding Path=AvailableRam}" />
    Finally, you'll need to set the view's data context to the RamManager instance. Something like..
    Code:
    public Window1( )
    {
          InitializeComponent();
    
          ramManager = new RamManager();
    
          DataContext = ramManager;
    
          ramManager.StartThread( );
    }
    For a better approach using the MVVM pattern, I'd suggest reading Josh Smith's excellent article.

    http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
    Last edited by Arjay; August 25th, 2010 at 08:36 PM.

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