user440096
user440096

Reputation:

Trying to bind from XAML to a member var of the same class (from the .xaml to the .xaml.cs)

In my XAML I have the code

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
    <StackPanel>
        <TextBlock Height="30" Name="tb1" Text="{Binding meetingX}" />
    </StackPanel>
</Grid>

In the .xaml.cs belong to the above .xaml I have

    public static Meeting theMeeting;
    public string meetingX;

    public MeetingOverview()
    {
        InitializeComponent();
        theMeeting = (Meeting)App.meetings.ElementAt(App.selectedMeetingIndex);
        meetingX = theMeeting.MeetingName.ToString();
    }

    public string MeetingX
    {
        get
        {
            return meetingX;
        }
        set
        {
            if (value != meetingX)
            {
                Debug.WriteLine("set meetingXto: " + value.ToString()); 
                meetingX= value;
            }
        }
    }

The Text comes up blank so its not reading the value in meetingX. I added a Debug.WriteLine to check that there is some text inside the var and there was.

Can anybody give me some tips on how to make what I intended to do work?

Many Thanks, -Code

Upvotes: 0

Views: 161

Answers (2)

Emond
Emond

Reputation: 50712

Turn the property into a DependencyProperty:

public String MeetingX
{
  get { return (String)this.GetValue(MeetingXProperty); }
  set { this.SetValue(MeetingXProperty, value); } 
}

public static readonly DependencyProperty MeetingXProperty = DependencyProperty.Register(
    "MeetingX", typeof(String), typeof(MeetingOverview),new PropertyMetadata(""));

Upvotes: 0

Louis Kottmann
Louis Kottmann

Reputation: 16648

You can only bind to properties:

Text="{Binding meetingX}" <!-- --> Text="{Binding MeetingX}"

You need to set the DataContext of your view:

public MeetingOverview()
    {
        theMeeting = (Meeting)App.meetings.ElementAt(App.selectedMeetingIndex);
        meetingX = theMeeting.MeetingName.ToString();
        this.DataContext = this;
        InitializeComponent();        
    }

If the value is going to change, you need to implement INotifyPropertyChanged on your class. Also you should take a look at MVVM, as such information should be placed in a ViewModel.

Both these subjects are extensively blogged about all over the web, so I trust in your inner google searcher ;)

Hope this helps,

Bab.

Upvotes: 1

Related Questions