我有基於大型查詢的datamodel,我希望顯示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;
}
}
這工作。我現在明白,GUI中沒有任何內容會與通知對象綁定。我想這對於GridView來說並沒有什麼不同,因爲GridView仍然以「綁定到Enumerable」結束了「Amount」。但是,這當然不會發生。 「{綁定量}」只是設置「路徑」屬性的簡寫。修復之後,bindingSOURCE是實現INotifyPropertyChanged的對象。謝謝 – Tormod 2011-03-05 22:44:26