如何手动刷新数据绑定?

时间:2011-03-05 20:43:23

标签: wpf inotifypropertychanged

我有基于查询的大数据模型,我希望将Linq查询的结果显示在网格中。 GUI将编辑属性,这将影响查询结果。但是,即使绑定执行得很好,调试器也不会显示PropertyChanged事件的订阅者(它是“null”)。我做了这个测试的例子。

我希望用户设置一组条件,然后点击“执行”按钮。在我的例子中,我预计网格中的项目数量会发生变化。

这是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>

这是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;        
}
}

2 个答案:

答案 0 :(得分:2)

根据问题标题,快速回答是使用BindingExpression.UpdateTarget方法。

答案 1 :(得分:1)

DataContext设置为this,然后将您的绑定更改为

<DataGrid ItemsSource="{Binding Amount}">