The following example successfully shows the property Title in the ListBox, but is there a way to show method GetTitle() so that I don't have to turn all my methods into properties?
e.g. neither of these seem to work:
<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>
code-behind:
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 + ")";
}
}
}