Change you
Listbox.ItemTemplate
as follows:
<ListBox.ItemTemplate>
<DataTemplate>
<Grid MaxWidth="200" Margin="10">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Image Source="{Binding Url}" />
<TextBlock MouseDown="txtblk_MouseDown" Grid.Row="1"
Text="{Binding Title}" />
<TextBox LostFocus="txtbox_LostFocus" Grid.Row="1"
Text="{Binding Title, Mode=TwoWay}"
Visibility="Collapsed" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
and add the following code to your code-behind:
private void txtblk_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
TextBox txt = (TextBox)((Grid)((TextBlock)sender).Parent).Children[2];
txt.Visibility = Visibility.Visible;
((TextBlock)sender).Visibility = Visibility.Collapsed;
}
private void txtbox_LostFocus(object sender, RoutedEventArgs e)
{
TextBlock tb = (TextBlock)((Grid)((TextBox)sender).Parent).Children[1];
tb.Visibility = Visibility.Visible;
((TextBox)sender).Visibility = Visibility.Collapsed;
}
For the changed to be reflected using data binding, you need to change the
MyPicture
class as follows:
public class MyPicture : ObservableBase
{
public Uri Url { get; set; }
private string title;
public string Title
{
get { return title; }
set { Set(ref title, value); }
}
}
and add the following class to support the
INotifyPropertyChanged
interface:
public abstract class ObservableBase : INotifyPropertyChanged
{
public void Set<TValue>(ref TValue field, TValue newValue, [CallerMemberName] string propertyName = "")
{
if (EqualityComparer<TValue>.Default.Equals(field, default(TValue)) || !field.Equals(newValue))
{
field = newValue;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
The
INotifyPropertyChanged
interface notifies the data binding system there is a change when the
PropertyChanged
event is raised. I've wrapped this up in a base class making the usage very simple. You can see this in the Title property
Set
method of the
MyPicture
class.
To use, click on the Picture's title text and you will be able to edit it. Once you click outside the editing TextBox, the changes will automatically be applied.