繁体   English   中英

绑定到ObservableCollection的列表框为空

[英]Listbox bound to ObservableCollection empty

我有以下xaml:

<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列表为空。 我没有任何错误,当我在代码中停下来时,我看到原因集合中填充了表中的项目。

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

看来您的绑定路径设置为POS_Price_Change_Reason ,而属性的名称是reasons 除非您的示例代码中未包含POS_Price_Change_Reason ,否则reasons是此属性的后备字段。

另外,请记住,您只能绑定到公共属性 ,而不能绑定到字段。 此外,如果更改属性的值,则需要通过对该属性调用PropertyChangedEventHandler事件来通知该更改视图:

PropertyChanged(new PropertyChangedEventArgs("YourPropertyName"));

问题似乎是您如何创建该属性。 我知道您将您的财产视为一个可观察的收藏,但这并不意味着它是自我可观察的! 因此,您需要通过在setter中执行以下操作来通知此属性更改时的UI:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM