2009-11-22 101 views
1

以下示例在ListBox中成功显示属性标题,但是有没有办法显示方法GetTitle()以便我不必将所有方法都转换为属性?有没有办法将一个方法绑定到ListBox的DataTemplate?

例如这些都不似乎工作:

<TextBlock Text="{Binding GetTitle}"/> 
<TextBlock Text="{Binding GetTitle()}"/> 

XAML:

<Window x:Class="TestBindMethod8938.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="Window1" Height="300" Width="300"> 
    <Grid> 
     <ListBox DockPanel.Dock="Top" ItemsSource="{Binding BackupTasks}" Margin="0 10 0 0"> 
      <ListBox.ItemTemplate> 
       <DataTemplate> 
        <TextBlock Text="{Binding Title}"/> 
       </DataTemplate> 
      </ListBox.ItemTemplate> 
     </ListBox> 
    </Grid> 
</Window> 

后台代码:

using System.Windows; 
using System.ComponentModel; 
using System.Collections.ObjectModel; 

namespace TestBindMethod8938 
{ 
    public partial class Window1 : Window, INotifyPropertyChanged 
    { 

     #region ViewModelProperty: BackupTasks 
     private ObservableCollection<BackupTask> _backupTasks = new ObservableCollection<BackupTask>(); 
     public ObservableCollection<BackupTask> BackupTasks 
     { 
      get 
      { 
       return _backupTasks; 
      } 

      set 
      { 
       _backupTasks = value; 
       OnPropertyChanged("BackupTasks"); 
      } 
     } 
     #endregion 


     public Window1() 
     { 

      InitializeComponent(); 
      DataContext = this; 

      BackupTasks.Add(new BackupTask(@"c:\test", @"c:\test2")); 

     } 


     #region INotifiedProperty Block 
     public event PropertyChangedEventHandler PropertyChanged; 

     protected void OnPropertyChanged(string propertyName) 
     { 
      PropertyChangedEventHandler handler = PropertyChanged; 

      if (handler != null) 
      { 
       handler(this, new PropertyChangedEventArgs(propertyName)); 
      } 
     } 
     #endregion 
    } 



    public class BackupTask 
    { 
     public string SourceFolder { get; set; } 
     public string TargetFolder { get; set; } 
     public int NumberOfFilesToBackup { get; set; } 
     public string Title 
     { 
      get 
      { 
       return SourceFolder + " --> " + TargetFolder + " (" + NumberOfFilesToBackup + ")"; 
      } 
      set 
      { 
      } 
     } 

     public BackupTask(string sourceFolder, string targetFolder) 
     { 
      SourceFolder = sourceFolder; 
      TargetFolder = targetFolder; 
     } 

     public string GetTitle() 
     { 
      return SourceFolder + " --> " + TargetFolder + " (" + NumberOfFilesToBackup + ")"; 
     } 


    } 

} 

回答

2

使用列表框的'DisplayMember'属性不是更容易吗? 我会建议使用属性而不是方法,所以数据绑定和NotifyPropertyChanged按预期工作。我不认为结合方法将实际工作...

这样的:

<ListBox DockPanel.Dock="Top" ItemsSource="{Binding BackupTasks}" 
     DisplayMemberPath="Title" Margin="0 10 0 0"> 

希望这有助于 [R

相关问题