Tormod
Tormod

Reputation: 4573

How do I manually refresh a databinding?

I have big query based datamodel, and I wish to display results of Linq queries into grids. The GUI will edit attributes, which will affect the query result. However, even though the binding executes just fine, the debugger shows no subscriber to the PropertyChanged event (it is "null"). I have made this test example.

I wish for the user to set a bunch of criteria and then hit an "execute" button. In my example, I expected the number of items in the grid to change.

Here is the xaml:

<Window x:Class="GridViewNotifyTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <StackPanel>
        <Button Click="Button_Click">Take 3</Button>
        <Button Click="Button_Click_1">Take 5</Button>
        <Button Click="Button_Click_2">FireNotify</Button>
    <DataGrid ItemsSource="{Binding}">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding}"/>
        </DataGrid.Columns>            
    </DataGrid>
    </StackPanel>
</Grid>
</Window>

And here is the C#:

namespace GridViewNotifyTest
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window,INotifyPropertyChanged
{
    private int _takeAmount;

    public MainWindow()
    {
        InitializeComponent();
        _takeAmount = 4;
        DataContext = Amount;            
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        _takeAmount = 3;
    }

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        _takeAmount = 5;
    }

    private void Button_Click_2(object sender, RoutedEventArgs e)
    {
        OnPropertyValueChanged("Amount");
    }

    protected virtual void OnPropertyValueChanged(string propertyName)
    {
        if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));  // THE DEBUGGER SHOWS THE PROPERTYCHANGED DELEGATE AS NULL.
    }

    public IEnumerable<int> Amount
    {
        get { return Enumerable.Range(1,10).Take(_takeAmount); }            
    }

    public event PropertyChangedEventHandler PropertyChanged;        
}
}

Upvotes: 1

Views: 435

Answers (2)

kyrylomyr
kyrylomyr

Reputation: 12632

According to question title, fast answer will be to use BindingExpression.UpdateTarget method.

Upvotes: 2

thumbmunkeys
thumbmunkeys

Reputation: 20764

Set the DataContext to this and then change your Binding to be

<DataGrid ItemsSource="{Binding Amount}">

Upvotes: 1

Related Questions