我有一个非常简单的类,我用一个 LINQ 查询填充它——一切都很好;
public class CatSummary : INotifyPropertyChanged
{
private string _catName;
public string CatName
{
get { return _catName; }
set { if (_catName != value) { _catName = value; NotifyPropertyChanged("CatName"); } }
}
private decimal _catAmount;
public decimal CatAmount
{
get { return _catAmount; }
set { if (_catAmount != value) { _catAmount = value; NotifyPropertyChanged("CatAmount"); } }
}
public event PropertyChangedEventHandler PropertyChanged;
// Used to notify Silverlight that a property has changed.
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
//MessageBox.Show("NotifyPropertyChanged: " + propertyName);
}
}
}
LINQ 位;
var myOC = new ObservableCollection<CatSummary>();
var initialQuery = BoughtItemDB.BoughtItems
.GroupBy(item => item.ItemCategory)
.Select(x => new CatSummary
{
CatName = x.Key,
CatAmount = x.Sum(amt => amt.ItemAmount)
});
foreach (var item in initialQuery) myOC.Add(item);
我正在尝试将我的 WPF 控件绑定到下面 XAML 中的自定义类;
<ListBox x:Name="boughtItemsListBox" ItemsSource="{Binding CatSummary}" Margin="5,27,-35,100" Width="450" Height="371" Grid.ColumnSpan="2" Grid.RowSpan="2">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Stretch" Width="440">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding CatName, StringFormat=g}" TextWrapping="Wrap" FontSize="{StaticResource PhoneFontSizeSmall}" VerticalAlignment="Top"/>
<TextBlock Grid.Column="1" Text="{Binding CatAmount, StringFormat=\{0:C\}}" Margin="1" FontSize="{StaticResource PhoneFontSizeSmall}" VerticalAlignment="Top"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
这给了我以下错误;BindingExpression 路径错误:在“MyApp.SpendAnalysis+CatSummary”上找不到“CatSummary”属性
根据我读过的内容,我认为我需要将我的类的属性变成 ObservableCollection 属性,但这似乎破坏了我的 LINQ 查询。我已经为此尝试了各种方法,也找不到任何教程来帮助我理解它应该如何工作。很高兴收到任何建议或指示。