views:

63

answers:

3

I'm trying to set the ItemsSource property of a DataGrid named dgIssueSummary to be an ObservableCollection named IssueSummaryList. Currently, everything is working when I set the ItemsSource property in my code-behind:

public partial class MainPage : UserControl
{
    private ObservableCollection<IssueSummary> IssueSummaryList = new ObservableCollection<IssueSummary>

    public MainPage()
    {
        InitializeComponent();
        dgIssueSummary.ItemsSource = IssueSummaryList
    }
}

However, I'd rather set the ItemsSource property in XAML, but I can't get it to work. Here's the XAML code I have:

<sdk:DataGrid x:Name="dgIssueSummary" AutoGenerateColumns="False"
                ItemsSource="{Binding IssueSummaryList}" >
    <sdk:DataGrid.Columns>
        <sdk:DataGridTextColumn Binding="{Binding ProblemType}" Header="Problem Type"/>
        <sdk:DataGridTextColumn Binding="{Binding Count}" Header="Count"/>
    </sdk:DataGrid.Columns>
</sdk:DataGrid>

What do I need to do to set the ItemsSource property to be the IssueSummaryList in XAML rather than C#?

+1  A: 

You need to make "IssueSummaryList" a property. If you do this, you can bind to it directly. You can't bind via Xaml to a private field.

You'll also need to set the DataContext to "this" (or use another method to get it to find the appropriate instance).

Reed Copsey
Isn't the DataContext thing only needed if you use the M-V-VM Pattern for binding ?He seems to use just code behind files
KroaX
@KroaX: No. The binding works via a DataContext. The MVVM pattern takes advantage of this, but Data Binding in WPF (and Silverlight) is always binding to a property on the DataContext being used by the UIElement.
Reed Copsey
+1  A: 

Your IssueSummaryList is private. You need to make it a Property with get and set

public ObservableCollection<IssueSummary> IssueSummaryList 
{
     get
     {
        // ...
     }
}
KroaX
+1  A: 

The XAML is correct, so the problem must be in the Binding.

  • Is the ObservableCollection exposed as a property?
  • How have you set the Binding? In the most simple case you use code like:

    this.DataContext=this;

in the Window_Load eventhandler

Dabblernl