0

有谁知道为什么我的 ListView 以下代码不起作用?我用 Snoop 进行了检查,ItemsSource 似乎很好(当我启动 Snoop 时,ListView 向我显示 MyViewModel.MyCollection,但是在使用 Visual Studio 调试时它什么也没显示?)

谢谢!

PS:MainWindow.xaml.cs 有 DataContext = MainViewModel

    <ListView Grid.Row="1" Margin="38,50,0,168" HorizontalAlignment="Left" Name="listViewSelectDate" Width="105"
              ItemsSource="{Binding Path=MyViewModel.MyCollection}" 
              SelectedItem="{Binding SelectedDate}" IsSynchronizedWithCurrentItem="True">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Date" DisplayMemberBinding="{Binding Path=CalcDate}"/>
            </GridView>
        </ListView.View>
    </ListView>

ViewModel 看起来像这样:

class MainViewModel : ViewModelBase
{
    public SummaryViewModel MyViewModel
    {
        get { return _myViewModel; }
        set { _myViewModel = value; RaisePropertyChanged("MyViewModel"); }
    }
    public MyDate SelectedDate
    {
        get { return _selectedDate; }
        set { _selectedDate = value; RaisePropertyChanged("SelectedDate"); }
    }
}

public class SummaryViewModel : ViewModelBase
{
    public ObservableCollection<MyDate> MyCollection { get; set; }
}

public class MyDate
{
    public DateTime CalcDate { get; set; }
}
4

2 回答 2

1

谁定的MyCollection?它不提供更改通知,因此绑定不知道它已被更改。改成:

private ObservableCollection<MyDate> _myCollection;
public ObservableCollection<MyDate> MyCollection
{
    get { return _myCollection; }
    set
    {
        _myCollection = value;
        OnPropertyChanged("MyCollection");
    }
}

或者,更好的是,将其设为只读:

private readonly ICollection<MyDate> _myCollection = new ObservableCollection<MyDate>();

public ICollection<MyDate> MyCollection
{
    get { return _myCollection; }
}
于 2009-08-04T15:09:33.890 回答
0

查看 Visual Studio 输出窗口,它将显示您可能遇到的任何 DataBinding 错误,这可能会帮助您解决问题。

于 2009-08-04T15:13:58.470 回答