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#?

3 Answers 3

3

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).

2
  • 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 Jun 14, 2010 at 18:28
  • @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. Jun 14, 2010 at 18:36
1

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

public ObservableCollection<IssueSummary> IssueSummaryList 
{
     get
     {
        // ...
     }
}
1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.