2009-11-22 109 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

相關問題