JpSiller
JpSiller

Reputation: 73

Data Binding not working in silverlight

I'm trying to do some simple databinding. I have a collection that returns an item with a property called MenuName. I have checked it is returned correctly. So here it is how I'm trying to do the binding. (By the Menu inherits from INotifyPropertyChanged.)

XAML

<Grid x:Name="LayoutRoot" DataContext="MenuItems">
        <StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Grid.Row="0" Margin="24,17,0,28">
            <TextBlock Text="Test" Typography.Capitals="SmallCaps"/>
            <TextBlock Text="{Binding MenuName }" Margin="0,12,0,0" FontSize="52"/>
            <CheckBox>Cache</CheckBox>
        </StackPanel>
    </Grid>

Code Behind:

#region Members
        MyAppWinConnectionClient MyAppWinService;
        #endregion Members

        #region Properties
        public ObservableCollection<Menu> MenuItems { get; set; }
        #endregion Properties

        public StandardUI()
        {
            MyAppWinService = new MyAppWinConnectionClient();
            this.InitializeComponent();           

            LoadTest();
        }

        private async void LoadTest()
        {
            try
            {
                MenuItems = await MyAppWinService.GetMenuEntriesAsync();
            }
            catch (FileNotFoundException ex)
            {

            }
        }

I think I'm missing something obvious. What do you think?

Upvotes: 1

Views: 143

Answers (2)

ΩmegaMan
ΩmegaMan

Reputation: 31721

Use the page's DataContext which each control will use if its datacontext is not set. Set the page's datacontext as such:

public StandardUI()
{
   DataContext = this;
   MyAppWinService = new MyAppWinConnectionClient();
   this.InitializeComponent();           

   LoadTest();
}

Then on the binding, extract the first menu item:

<Grid x:Name="LayoutRoot">
        <StackPanel>
            <TextBlock Text="Test" Typography.Capitals="SmallCaps"/>
            <TextBlock Text="{Binding MenuItems[0].MenuName }" />
            <CheckBox>Cache</CheckBox>
        </StackPanel>
    </Grid>

But one should look into MVVM. I give a short concise example of binding, datacontexts and MVVM on my blog article entitled Xaml: ViewModel Main Page Instantiation and Loading Strategy for Easier Binding.

Upvotes: 1

user5153847
user5153847

Reputation:

I recommend you to use "StandardUI" as a DataContext of your view (or LayoutRoot) and then use "MenuItems" as the ItemsSource of the StackPanel. Then you can add many properties as you want to StandardUI and use them over another controls. Like mvvm pattern. ;)

Upvotes: 1

Related Questions