1

在这里,我配置了一个列表框,其中 DataTemplate 中的 TextBlox 设置为绑定“名称”属性。但相反,它显示了完整的类名“DomainClasses.Entities.Program”。为什么?

<Grid DataContext="{Binding _CurrentProgram }">
.....
.....
    <ListBox x:Name="ProgramsListBox" Width="600" Height="400" Margin="50,0,50,0" ItemsSource="{Binding _Programs}" VerticalAlignment="Top">
       <DataTemplate>
          <StackPanel>
             <TextBlock Text="{Binding Name}"></TextBlock>
          </StackPanel>
       <DataTemplate>
    </ListBox>
----
----
</Grid>

这是 ViewModel 类

public class MainPageViewModel : INotifyPropertyChanged
{
    public MainPageViewModel()
    {
        _currentProgram = new Program();
        _Programs = new ObservableCollection<Program>();
    }

    public async void SaveProgram(bool isEditing)
    {
        _Programs.Add(_currentProgram);
        OnPropertyChanged();
    }

    private Program _currentProgram;
    public Program _CurrentProgram
    {
        get { return _currentProgram; }
        set
        {

            _currentProgram = value;
            OnPropertyChanged();

        }
    }

    private ObservableCollection<Program> _programs;
    public ObservableCollection<Program> _Programs
    {
        get
        {
            return _programs;
        }
        set
        {
            this._programs = value;
            OnPropertyChanged();
        }
    }

    // Implement INotifyPropertyChanged Interface
    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged([CallerMemberName] string caller = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(caller));
        }
    }
}
4

2 回答 2

2

这就是你需要的:

<ListBox>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Button/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

注意到ListBox.ItemTemplate周围的DataTemplate

你有什么:

<ListBox x:Name="ProgramsListBox" Width="600" Height="400" Margin="50,0,50,0" ItemsSource="{Binding _Programs}" VerticalAlignment="Top">
   <DataTemplate>
      <StackPanel>
         <TextBlock Text="{Binding Name}"></TextBlock>
      </StackPanel>
   <DataTemplate>
</ListBox>

创建 aListBox作为DataTemplate子项(与 中的项是 的ItemsSource子项相同ListBox)。如果我没记错的话,当你设置ItemsSourcea时ListBox,所有以其他方式设置的项目都会被删除。所以你最终得到的是 a里面ListBox有一堆Programs,没有ItemsTemplate设置,所以它只是显示绑定类的名称。

于 2013-05-11T04:04:02.120 回答
0

You need to add the data template inside listview.itemtemplate and then do the binding. Right now you are adding the data template as a child of the listview.

于 2013-05-16T19:03:06.710 回答