You are attempting to program a WPF application like you would a Windows Forms app. Believe me, you can accomplish your goal much easier if you actually learn some of the WPF development patterns (such as MVVM).
For example, this can be easily accomplished using an ObservableCollection holding all (not sure how you are doing this) FileInfo instances (one for each file).
You then bind a ItemsControl's ItemsSource property to this collection. Now, whenever you add a new FileInfo instance to the ObservableCollection the ItemsControl will add a new row and bind that row to the instance.
Of course, the default template for each row just calls .ToString() on each instance, so you'll get a bunch of rows that contains "System.IO.FileInfo". To show information about each FileInfo, you can add a DataTemplate to ItemsSource.ItemTemplate and add controls that bind to the public properties of the FileInfo.
It is VERY important to understand some of these basic patterns when developing WPF applications. Attempting to interact with the UI from the codebehind in the manner you are attempting is VERY HARD to do. Many of the UI patterns for WPF applications are optimized for use in XAML; attempting to interact with these (such as attached properties) from the codebehind can be extremely confusing and counterintuitive.
Here's a simple MVVM sample I updated. To use this, create a new solution (3.5 or greater) called SimpleMVVM. Create a new class in the root of the project called ViewModel and add the following code to the file:
/// <summary>
/// A simple ViewModel to demonstrate MVVM
/// </summary>
public sealed class ViewModel : DependencyObject, IDataErrorInfo
{
#region Properties
#region DirectoryName
/// <summary>
/// The <see cref="DependencyProperty"/> for <see cref="DirectoryName"/>.
/// </summary>
public static readonly DependencyProperty DirectoryNameProperty =
DependencyProperty.Register(
DirectoryNameName,
typeof(string),
typeof(ViewModel),
new UIPropertyMetadata(null));
/// <summary>
/// The name of the <see cref="DirectoryName"/> <see cref="DependencyProperty"/>.
/// </summary>
public const string DirectoryNameName = "DirectoryName";
/// <summary>
///
/// </summary>
public object DirectoryName
{
get { return (object)GetValue(DirectoryNameProperty); }
set { SetValue(DirectoryNameProperty, value); }
}
#endregion
#region SelectedFile
/// <summary>
/// The <see cref="DependencyProperty"/> for <see cref="SelectedFile"/>.
/// </summary>
public static readonly DependencyProperty SelectedFileProperty =
DependencyProperty.Register(
SelectedFileName,
typeof(FileInfo),
typeof(ViewModel),
new UIPropertyMetadata(null));
/// <summary>
/// The name of the <see cref="SelectedFile"/> <see cref="DependencyProperty"/>.
/// </summary>
public const string SelectedFileName = "SelectedFile";
/// <summary>
///
/// </summary>
public FileInfo SelectedFile
{
get { return (FileInfo)GetValue(SelectedFileProperty); }
set { SetValue(SelectedFileProperty, value); }
}
#endregion
/// <summary>
/// The files found under <see cref="DirectoryName"/>.
/// </summary>
public ObservableCollection<FileInfo> Files { get; private set; }
/// <summary>
/// Holds the last filename error for IDataErrorInfo
/// </summary>
private string _lastDirectoryNameError = null;
#endregion
#region ctor
/// <summary>
/// Initializes a new instance of the <see cref="ViewModel"/> class.
/// </summary>
public ViewModel()
{
Files = new ObservableCollection<FileInfo>();
}
#endregion
#region methods
/// <summary>
/// Invoked whenever the effective value of any dependency property on this <see cref="T:System.Windows.DependencyObject"/> has been updated. The specific dependency property that changed is reported in the event data.
/// </summary>
/// <param name="e">Event data that will contain the dependency property identifier of interest, the property metadata for the type, and old and new values.</param>
protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
{
base.OnPropertyChanged(e);
if (e.Property == DirectoryNameProperty)
UpdateFiles(e.OldValue as string, e.NewValue as string);
}
/// <summary>
/// Updates <see cref="Files"/> when <see cref="DirectoryName"/> changes.
/// </summary>
/// <param name="oldDirectoryName">The old value of <see cref="DirectoryName"/></param>
/// <param name="newDirectoryName">The new value of <see cref="DirectoryName"/></param>
private void UpdateFiles(string oldDirectoryName, string newDirectoryName)
{
if (string.IsNullOrWhiteSpace(newDirectoryName))
{
Files.Clear();
return;
}
if (!string.IsNullOrEmpty(oldDirectoryName) &&
oldDirectoryName.Equals(newDirectoryName, StringComparison.OrdinalIgnoreCase))
return;
try
{
var di = new DirectoryInfo(Directory.Exists(newDirectoryName) ? newDirectoryName : Path.GetDirectoryName(newDirectoryName));
// dirty hack
if (di.ToString().Equals(".", StringComparison.OrdinalIgnoreCase))
{
_lastDirectoryNameError = "Not a valid directory name.";
return;
}
Files.Clear();
foreach (var file in di.GetFiles())
Files.Add(file);
_lastDirectoryNameError = null;
}
catch (Exception ioe)
{
_lastDirectoryNameError = ioe.Message;
}
}
#endregion
#region IDataErrorInfo
/// <summary>
/// Gets an error message indicating what is wrong with this object.
/// </summary>
/// <returns>An error message indicating what is wrong with this object. The default is an empty string ("").</returns>
string IDataErrorInfo.Error
{
get
{
return _lastDirectoryNameError;
}
}
/// <summary>
/// Gets the error message for the property with the given name.
/// </summary>
/// <returns>The error message for the property. The default is an empty string ("").</returns>
string IDataErrorInfo.this[string columnName]
{
get
{
if (columnName.Equals(DirectoryNameName, StringComparison.OrdinalIgnoreCase))
return _lastDirectoryNameError;
return null;
}
}
#endregion
}
Next, open MainWindow.xaml and replace the xaml with the following:
<Window
x:Class="SimpleMVVM.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:t="clr-namespace:SimpleMVVM"
Title="MainWindow"
Height="350"
Width="525">
<Window.DataContext>
<t:ViewModel />
</Window.DataContext>
<Window.Resources>
<Style
x:Key="alternatingListViewItemStyle"
TargetType="{x:Type ListViewItem}">
<Style.Triggers>
<Trigger
Property="ItemsControl.AlternationIndex"
Value="1">
<Setter
Property="Background"
Value="LightGray"></Setter>
</Trigger>
<Trigger
Property="ItemsControl.AlternationIndex"
Value="2">
<Setter
Property="Background"
Value="White"></Setter>
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition
Height="auto" />
<RowDefinition />
<RowDefinition
Height="auto" />
</Grid.RowDefinitions>
<TextBox
Margin="4"
Text="{Binding DirectoryName, ValidatesOnDataErrors=True, ValidatesOnExceptions=True,UpdateSourceTrigger=PropertyChanged}">
<TextBox.Style>
<Style
TargetType="TextBox">
<Setter
Property="ToolTip"
Value="Please enter a directory name" />
<Style.Triggers>
<Trigger
Property="Validation.HasError"
Value="true">
<Setter
Property="ToolTip"
Value="{Binding (Validation.Errors)[0].ErrorContent, RelativeSource={x:Static RelativeSource.Self}}" />
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
<ListView
Margin="4"
Grid.Row="1"
AlternationCount="2"
ItemsSource="{Binding Files}"
ItemContainerStyle="{StaticResource alternatingListViewItemStyle}"
SelectedItem="{Binding SelectedFile}">
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition
Width="100" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Label
Grid.Row="0">Name</Label>
<Label
Grid.Row="1">Size</Label>
<Label
Grid.Row="2">Read Only</Label>
<Label
Grid.Row="3">Type</Label>
<TextBlock
Grid.Row="0"
Grid.Column="1"
Text="{Binding Name}" />
<TextBlock
Grid.Row="1"
Grid.Column="1"
Text="{Binding Length}" />
<CheckBox
Grid.Row="2"
Grid.Column="1"
IsChecked="{Binding IsReadOnly}"
IsEnabled="False" />
<TextBlock
Grid.Row="3"
Grid.Column="1"
Text="{Binding Extension}" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<StatusBar
Grid.Row="2">
<StatusBarItem
Content="{Binding SelectedFile.FullName, StringFormat='Selected: {0}', FallbackValue='Please enter a directory and select a file.'}" />
</StatusBar>
</Grid>
</Window>
(excuse me everybody for the code dump!) Compile, fix errors and run it.