Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Binding: How to bind a name from a list of filepaths to text of TextBlock in ListBox?

i'm trying to bind a name of a file given by a filepath to a TextBlock. The filepath is stored in a list which is bound to the ItemsSourceProperty of a ListBox. The TextBlock is set as DataTemplate. My question is: How can i get the name without path and extension and bind it to the TextBlock?

The XAML code for better explanation:

<ListBox Name="MyListBox" Margin="2">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

And the code behind:

string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
List<string> PathList = Directory.GetFiles(path, "*.txt").ToList();

Binding myBind = new Binding();
myBind.Source = PathList;

myListBox.SetBinding(ListBox.ItemsSourceProperty, myBind);
like image 639
Steffen Gerdes Avatar asked Dec 31 '25 23:12

Steffen Gerdes


2 Answers

One uses a converter to change the text of a selected listbox item which is fully pathed to just the filename.

In the following example there is a list and a textbox next to it. Once an item is selected, the textbox bound to the list's SelectedItem extracts the pathed string which is passed to a converter which returns just the filename to show.

Example

enter image description here

XAML

<Window x:Class="WPFStack.ListBoxQuestions"
 xmlns:local="clr-namespace:WPFStack"
 xmlns:converters="clr-namespace:WPFStack.Converters"
.../>

<StackPanel Orientation="Horizontal">
    <StackPanel.Resources>
        <converters:PathToFilenameConverter x:Key="FilenameConverter" />

        <x:Array x:Key="FileNames" Type="system:String">
            <system:String>C:\Temp\Alpha.txt</system:String>
            <system:String>C:\Temp\Beta.txt</system:String>
        </x:Array>

    </StackPanel.Resources>

    <ListBox  Name="lbFiles"
              ItemsSource="{StaticResource FileNames}" />

    <TextBlock Text="{Binding SelectedItem, 
                              ElementName=lbFiles,
                              Converter={StaticResource FilenameConverter}}"
                Margin="6,0,0,0" />

</StackPanel>

Converter

namespace WPFStack.Converters
{
public class PathToFilenameConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        object result = null;

        if (value != null)
        {
            var path = value.ToString();

            if (string.IsNullOrWhiteSpace(path) == false)
                result = Path.GetFileNameWithoutExtension(path);
        }

        return result;

    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value;
    }
}
}

ItemTemplate Use of Converter

The converter is reused in the template as such

 <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Converter={StaticResource FilenameConverter}}"/>
        </DataTemplate>
  </ListBox.ItemTemplate>
like image 107
ΩmegaMan Avatar answered Jan 02 '26 14:01

ΩmegaMan


If you just want to add a static list to list box you should do it like this.

XAML:

    <ListBox x:Name="lb" ItemsSource="{Binding Collection}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding}" />
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

The code behind constructor for in the main window:

        public MainWindow()
        {
            InitializeComponent();

            List<string> l = new List<string>();
            l.Add("string path 1");
            l.Add("string path 2");
            l.Add("string path 3");
            l.Add("string path 4");
            lb.ItemsSource = l;

        }

You should be aware that there is a much better way of doing these things. I would honestly suggest you go look MVVM and doing a proper binding to a ViewModel.

like image 30
Matt Wilkinson Avatar answered Jan 02 '26 14:01

Matt Wilkinson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!