2012-08-03 111 views
1

我有下面的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

回答

0

原因需要屬性(添加{ get; set;})。另外,看看Visual Studio輸出 - 它顯示綁定錯誤,應該有一些關於失敗的綁定原因的信息。

+0

我知道它必須是一個簡單的修復,因爲我在另一個頁面上做了同樣的事情,沒有任何問題。感謝您的快速幫助。 – mdhunt 2012-08-03 17:22:58

0

看起來您的裝訂路徑設置爲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

0

的問題似乎是你是如何創建的屬性。 我知道你把你​​的財產作爲一個可觀察的收藏,但這並不意味着它是由它自我觀察的! 所以你需要通知UI時,此屬性是由在二傳手這樣做一些改變:

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

我不記得確切的代碼,因爲我沒有使用WPF一段時間,但它是INotifyPropertyChanged中的方法,祝你好運!

相關問題