列表框绑定到的ObservableCollection空

问题描述:

我有下面的XAML代码:列表框绑定到的ObservableCollection空

<Window x:Class="Retail_Utilities.Dialogs.AdjustPriceDialog" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    ShowInTaskbar="False" 
    WindowStartupLocation="CenterOwner" Name="Adjust_Price" 
    Title="Adjust Price" Background="#ee0e1c64" AllowsTransparency="True" WindowStyle="None" Height="330" Width="570" KeyDown="Window_KeyDown" Loaded="Window_Loaded"> 

<Grid Height="300" Width="550"> 
<ListBox HorizontalAlignment="Right" Margin="0,110,35,60" Name="lstReasons" Width="120" VerticalAlignment="Stretch" 
      ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Window, AncestorLevel=1}, Path=reasons}"> 
     <ListBox.ItemTemplate> 
      <DataTemplate> 
       <StackPanel> 
        <TextBlock Text="{Binding Path=POS_Price_Change_Reason}" /> 
       </StackPanel> 
      </DataTemplate> 
     </ListBox.ItemTemplate> 
    </ListBox> 
</Grid> 
</Window> 

下面是相关的C#:

namespace Retail_Utilities.Dialogs 
{ 
public partial class AdjustPriceDialog : Window, INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 

    public ObservableCollection<Twr_POS_Price_Change_Reason> reasons; ... 

最后,这里是从另一个页面打开该窗口中的代码:

AdjustPriceDialog apd = new AdjustPriceDialog(); 
apd.Owner = (Window)this.Parent; 
apd.reasons = new ObservableCollection<Twr_POS_Price_Change_Reason>(); 
var pcr = from pc in ctx.Twr_POS_Price_Change_Reasons where pc.Deactivated_On == null select pc; 
foreach (Twr_POS_Price_Change_Reason pc in pcr) 
{ 
    apd.reasons.Add(pc); 
} 
apd.AdjustingDetail = (Twr_POS_Invoice_Detail)lstDetails.SelectedItem; 
if (apd.ShowDialog() == true) 
{ 

} 

当对话框打开时,我的lstReasons列表为空。我没有遇到任何错误,当我在代码中放置一个停止符号时,我发现原因集合中填充了表中的项目。

+0

你有更改通知你的理由财产?你也可以在该属性的'get'上设置一个断点来查看它被引用的时间。 – 2012-08-03 16:16:51

原因需要属性(添加{ get; set;})。另外,看看Visual Studio输出 - 它显示绑定错误,应该有一些关于失败的绑定原因的信息。

+0

我知道它必须是一个简单的修复,因为我在另一个页面上做了同样的事情,没有任何问题。感谢您的快速帮助。 – mdhunt 2012-08-03 17:22:58

看起来您的装订路径设置为POS_Price_Change_Reason,而您的财产的名称是reasons。除非在示例代码中没有包含POS_Price_Change_Reason,并且reasons是此属性的后备字段。

另外,请记住,您可以绑定到公共性能,并不领域。此外,如果您更改属性的值,你需要通知这个变化的看法,通过调用你的PropertyChangedEventHandler事件该属性:

PropertyChanged(new PropertyChangedEventArgs("YourPropertyName")); 
+1

代码绑定到'ItemsSource'属性中的'reason'。绑定到'POS_Price_Change_Reason'试图绑定到'Twr_POS_Price_Change_Reason'类的一个属性。 – 2012-08-03 16:30:29

+0

你说得对,我读得太快了一点。我的建议的其余部分仍然应该保持。 – ceyko 2012-08-03 16:51:35

+0

将{get; set;}添加到原因的定义就是所有需要的(将其更改为字段中的属性)。在这种情况下不需要调用propertychanged,因为我相信'ObservableCollection'可以在内部执行此操作。 – mdhunt 2012-08-03 17:25:47

的问题似乎是你是如何创建的属性。 我知道你把你​​的财产作为一个可观察的收藏,但这并不意味着它是由它自我观察的! 所以你需要通知UI时,此属性是由在二传手这样做一些改变:

public ObservableCollection<Twr_POS_Price_Change_Reason> reasons 
{ 
get{....} 
set 
{ 
Notify('reasons') 
} 
} 

我不记得确切的代码,因为我没有使用WPF一段时间,但它是INotifyPropertyChanged中的方法,祝你好运!