0

我无法从绑定到 ListBox 的自定义对象中的可观察集合中获得任何显示。当我的视图模型中有一个字符串集合时,这可以正常工作,但是当我尝试通过自定义对象访问该属性时没有显示名称。我在输出窗口中没有收到任何错误。

这是我的代码:

自定义对象

public class TestObject
{
    public ObservableCollection<string> List { get; set; }

    public static TestObject GetList()
    {
        string[] list = new string[] { "Bob", "Bill" };

        return new TestObject
        {
            List = new ObservableCollection<string>(list)
        };
    }
}

Xaml

<Window x:Class="TestWPF.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>
    <ListBox Height="100" HorizontalAlignment="Left" Margin="120,61,0,0" Name="listBox1" VerticalAlignment="Top" Width="120" ItemsSource="{Binding Path=TObj.List}" />
</Grid>

Xaml.cs

    public partial class MainWindow : Window
{
    private ModelMainWindow model;

    public MainWindow()
    {
        InitializeComponent();
        model = new ModelMainWindow();
        this.DataContext = model;
        this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
    }

    public void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        this.model.Refresh();
    }
}

视图模型

    public class ModelMainWindow : INotifyPropertyChanged
{
    private TestObject tObj;

    public event PropertyChangedEventHandler PropertyChanged;

    public TestObject TObj
    {
        get
        {
            return this.tObj;
        }

        set
        {
            this.tObj = value;
            this.Notify("Names");
        }
    }

    public void Notify(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }

    public void Refresh()
    {
        this.TObj = TestObject.GetList();
    }
}
4

2 回答 2

1

无法绑定到私有属性。此外,更改通知针对错误的属性,更改"Names""TObj". (另外我建议将List属性设置为仅获取(由readonly字段支持),或实施INoptifyPropertyChanged以使更改不会丢失)

于 2012-06-01T15:10:20.800 回答
0

List是私人的。将其设为公共属性,否则 WPF 看不到它。

于 2012-06-01T15:10:13.160 回答