tags:

views:

578

answers:

1

Hello,

Another post describes how to access a codebehind variable in XAML.

However, I'd like to access a variable in codebehind object from XAML. The codebehind object, called FeedData, is declared as a dependency property of type FeedEntry. This class is just a container class with string and datetime properties.

Codebehind's property definitition is this:

public FeedEntry FeedData
        {
            get { return (FeedEntry)GetValue(FeedDataProperty); }
            set { SetValue(FeedDataProperty, value); }
        }
        public static readonly DependencyProperty FeedDataProperty =
            DependencyProperty.Register("FeedData", typeof(FeedReaderDll.FeedEntry), typeof(FeedItemUserControl), 
      new FrameworkPropertyMetadata(new FeedEntry(){ Title="Hi!", Published=DateTime.Now }));

In XAML I'm doing this, which doesn't work:

<UserControl x:Class="FeedPhysics.UserControls.FeedItemUserControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="40" Width="200"
    Background="Blue"
    DataContext="{Binding RelativeSource={RelativeSource Self}}"
    x:Name="xRoot">
    <StackPanel>
     <TextBlock Text="{Binding Title}" Foreground="White"/>
     <TextBlock Text="{Binding Published}" Foreground="White"/>
    </StackPanel>
</UserControl>

But if I override Window's datacontext setting in codebehind's contructor, it will work! Like this:

xRoot.DataContext = FeedData;

I understand why it works when datacontext is set in codebehing. But I'd like to find out a way to grab variables within an object that is declared in codebehind. Because, everything should be doable from XAML, right?

Thanks for answers in advance.

A: 

Try setting the StackPanel's DataContext to the FeedData object:

<StackPanel DataContext="{Binding FeedData}">

...

This will force the StackPanel to look at the DependencyProperty, and all elements in it will be referenced as properties of FeedData.

As long as you define the DataContext as "FeedData" somewhere in the logical tree above the visual elements you are binding to properties of it, it will work.

Guy Starbuck
That's it! Thanks for help!
Pompair