将嵌套属性绑定到列表框的数据

时间:2012-06-01 15:05:55

标签: c# wpf xaml data-binding mvvm

我无法从绑定到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();
    }
}

2 个答案:

答案 0 :(得分:1)

无法绑定到私有属性。此外,更改通知会定位错误的属性,将"Names"更改为"TObj"。 (另外我建议将List属性设为get-only(由readonly字段支持),或者实现INoptifyPropertyChanged以便更改不会丢失)

答案 1 :(得分:0)

您的List是私密的。使它成为公共财产,否则WPF无法看到它。