Selecting listbox item inside datatemplate - wpf

I have a listbox that uses a data template. The template is very simple and consists of an Image and a TextBlock. They are both bound to an XML document. The template is as follows:
<Window.Resources>
<XmlDataProvider x:Key="NinjaData" Source="\Data\Ninjas.xml" XPath="/Ninjas"/>
<DataTemplate x:Key="NinjaDataTemplate">
<StackPanel>
<StackPanel Orientation="Horizontal" Margin="0">
<Image Source="{Binding XPath=ImageFile}" Margin="5" Width="50"/>
<TextBlock Text="{Binding XPath=#Name}" Margin="5" FontFamily="OCR A Std" Foreground="#FF9114" FontSize="14" Name="NinjaName"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</Window.Resources>
The Listbox is as follows:
<ListBox Background="{x:Null}" BorderBrush="{x:Null}"
ItemsSource="{Binding Source={StaticResource NinjaData}, XPath=Ninja}"
ItemTemplate="{StaticResource NinjaDataTemplate}"
>
<ListBox.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Gray"></SolidColorBrush>
</ListBox.Resources>
<ListBox.Effect>
<DropShadowEffect ShadowDepth="1" Color="#FF282828"/>
</ListBox.Effect>
</ListBox>
I'm having trouble working out how to retrieve the content of the TextBlock inside the data template when I click on it in the listbox. I want to display it in a label somewhere else on the page, but I can't work out how to access that textblock.
Can anyone help and point me in the right direction? I feel like I'm going round in circles at the moment.
Thanks for any help.

As you have a ListBox you can use the selection, just name the ListBox and bind to the SelectedItem:
<ListBox Name="lb" ... />
<Label DataContext="{Binding SelectedItem, ElementName=lb}"
Content="{Binding XPath=#Name}"/>
This does not retrieve the Text of the TextBlock in the template but gets it from the same source as the template. (You could actually target the TextBlock in the Template itself but i would not recommend it)

Add a MouseLeftButtonUp event handler to your textblock inside your datatemplate like :
<TextBlock Text="{Binding XPath=#Name}" Margin="5" FontFamily="OCR A Std" Foreground="#FF9114" FontSize="14" Name="NinjaName" MouseLeftButtonUp="TextBlock_MouseLeftButtonUp"/>
Now your TextBlock_MouseLeftButtonUp should look like:
private void TextBlock_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
TextBlock txt = sender as TextBlock;
}
And now do whatever you like to do with txt

Related

How can I access the controls in a listbox control generated by an itemtemplate

I have a listbox and a dataTemplate defined like so:
<Window.Resources>
<DataTemplate x:Key="propertyTemplate">
<StackPanel Margin="8" Orientation="Horizontal">
<CheckBox Name="Chosen"/>
<TextBlock Text="{Binding Path=MAP}" Margin="10,0,0,0"/>
</StackPanel>
</DataTemplate>
</Window.Resources>
<ListBox x:Name="listBox" HorizontalAlignment="Left" Height="100" Margin="388,203,0,0" VerticalAlignment="Top" Width="522"
ItemsSource="{Binding}"
ItemTemplate="{StaticResource propertyTemplate}"/>
I populate the listbox using a linq query:
Dim propertyList = (from a In db.properties
select a).ToList()
listbox.datacontext = propertyList
I want to check and set the value of the "Chosen" checkbox for each item in the listbox. Is there a way for me to do this?
Don't do it, bind IsChecked to a property on your item class, then iterate over your source list.

Getting current Object in Control template

<ControlTemplate TargetType="{x:Type ListBoxItem}">
<StackPanel>
<StackPanel Margin="0,0,28,0" Orientation="Horizontal" Visibility="{Binding IsEditable,Converter={StaticResource BooleanToVisibilityConverter}}">
<TextBlock Foreground="Gray" Text="{Binding DateCreated,Converter={StaticResource DateTimeConverter}}" FontFamily="/Assets/Fonts/Berthold Akzidenz Grotesk BE Regular.ttf" FontSize="16"/>
<TextBlock Text=":" Foreground="Gray"/>
<TextBlock Width="20"/>
<TextBox ScrollViewer.HorizontalScrollBarVisibility="Disabled" BorderThickness="0" Name="TrainerNoteText" Text="{Binding TrainerNote}" FontFamily="/Assets/Fonts/Berthold Akzidenz Grotesk BE Regular.ttf" Foreground="Black" FontSize="16" TextWrapping="Wrap" KeyUp="EditTrainerNote" Width="400"/>
</StackPanel>
</StackPanel>
</ControlTemplate>
The above control template is in a listview. The textbox inside is editable. So when user presses the enter key, I need to get the current object associated with that. How to do this?
You can listen to KeyDown RoutedEvent at ListView level.
http://msdn.microsoft.com/en-us/library/system.windows.input.keyboard.keydown.aspx
Its an attached event and its handler can be placed anywhere in VisualTree.
Here is an example:
<StackPanel TextBox.KeyDown="OnKeyDownHandler">
<TextBox Width="300" Height="20"/>
</StackPanel>
And this is the handler:
public void OnKeyDownHandler(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
TextBox tbx = (TextBox)sender;
tbx.....
}
}
You know, you really should define what your items look like in a DataTemplate defined in the ListBox.ItemTemplate property and not the ListBoxItem.Template property. Based on the example from the linked page:
<ListBox Width="400" Margin="10" ItemsSource="{Binding YourCollectionProperty}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=TaskName}" />
<TextBlock Text="{Binding Path=Description}"/>
<TextBlock Text="{Binding Path=Priority}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
When Binding a collection property to the ListBox.Items property, all of the UI elements inside the DataTemplate will have access to the properties of the type that is in the collection. In this example, the type that populates the YourCollectionProperty collection has TaskName, Description and Priority properties in it. You can replace these properties with those from the type that is in your collection property.
If you set up your properties to implement the INotifyPropertyChanged interface (or use DependencyProperties then any updates in the UI elements will automatically be updated in the data objects in the view model/code behind. Therefore, there is no need to add KeyDown or KeyUp handlers. For more information, please read the Data Binding Overview page on MSDN.

WPF UserControl or ControlTemplate... (not sure)

I have a listbox where I have to add about 20 static custom items. All the items are based on the same template (something like that) :
<Border>
<StackPanel Orientation="Horizontal">
<Image Source="" Height="30" />
<TextBlock Text="" VerticalAlignment="Center" />
</StackPanel>
</Border>
I don't want to repeat that 20 times in the ListBox.Items I would like to have some kind of UserControl where I could do something Like the following where I could set some custom properties :
<ListBox>
<ListBox.Items>
<MyListBoxTemplate x:Name="Item1" ItemText="Item #1" ItemImageSource="/Image1.jpg" />
<MyListBoxTemplate x:Name="Item2" ItemText="Item #2" ItemImageSource="/Image2.jpg" />
...
</ListBox.Items>
</ListBox>
But I don't wan't to create a userControl just for that!!! Is there an easy way to put that template in the Window.Resources?
Thanks
If you are ONLY using it for that SPECIFIC listbox, you can just assign the ItemTemplate property. This will need to work in conjunction with a collection of custom objects defined in your resources somewhere else. This will save you from creating a custom UserControl, but you will need an object that can be defined in XAML and a list of them in XAML anyway. To be honest, creating a UserControl is relatively painless and may be easier, but it is possible without doing so.
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate TargetType="CustomObjectType">
<Border>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding ImageSource}" Height="30" />
<TextBlock Text="{Binding TextContent}" VerticalAlignment="Center" />
</StackPanel>
</Border>
<DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
EDIT: If you are going to use it in more than one place, put the DataTemplate in your Application resources and ive it a key, then assign the ItemTemplate property to {StaticResource MyListBoxItemsTemplateKey}
Not my favorite approach since it uses the XmlDataProvider and XPath syntax (which I tend to always forget). But you can embed your static data as xml within your Window.Resources like so:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Window.Resources>
<XmlDataProvider x:Key="MyStaticData" XPath="StaticItems" >
<x:XData>
<StaticItems xmlns="">
<StaticItem>
<ItemText>Item #1</ItemText>
<ItemImageSource>/Image1.jpg</ItemImageSource>
</StaticItem>
<StaticItem>
<ItemText>Item #2</ItemText>
<ItemImageSource>/Image2.jpg</ItemImageSource>
</StaticItem>
</StaticItems>
</x:XData>
</XmlDataProvider>
</Window.Resources>
<Grid>
<ListBox>
<ListBox.ItemsSource>
<Binding Source="{StaticResource MyStaticData}" XPath="StaticItem" />
</ListBox.ItemsSource>
<ListBox.ItemTemplate>
<DataTemplate>
<Border>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding XPath=ItemImageSource}" Height="30" />
<TextBlock Text="{Binding XPath=ItemText}" VerticalAlignment="Center" />
</StackPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
Then within your ListBox bind to the XmlDataProvider you specified and use the XPath notation within the bindings to drill down to the data you want the controls to bind to.
This site has a couple good examples too:
http://vbcity.com/blogs/xtab/archive/2010/12/24/more-xpath-examples-in-a-wpf-application.aspx
Hope this helps!

bind textblock to current listbox item in pure xaml

i have some data saved in a xml file.
Those will be displayed in a listbox.
Now, when i change the listbox Selectedindex, i would like to update the other information in the textblock based on the selectedindex.
is there any way to do this in pure xaml?
if not, how would i bind the Textblock to the selecteditem in the listbox ?
EDIT:
How would i navigate through the Data without using the listbox? i mean using a button to move to next item and other button to move backward..!!
any help is really appreciated..
<Window x:Class="WpfSingleInstance.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>
<StackPanel
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Background="Cornsilk">
<StackPanel.Resources>
<XmlDataProvider x:Key="InventoryData" XPath="Inventory/Books">
<x:XData>
<Inventory xmlns="">
<Books>
<Book ISBN="0-7356-0562-9" Stock="in" Number="9">
<Title>XML in Action</Title>
<Summary>XML Web Technology</Summary>
</Book>
<Book ISBN="0-7356-1370-2" Stock="in" Number="8">
<Title>Programming Microsoft Windows With C#</Title>
<Summary>C# Programming using the .NET Framework</Summary>
</Book>
<Book ISBN="0-7356-1288-9" Stock="out" Number="7">
<Title>Inside C#</Title>
<Summary>C# Language Programming</Summary>
</Book>
</Books>
</Inventory>
</x:XData>
</XmlDataProvider>
</StackPanel.Resources>
<TextBlock FontSize="18" FontWeight="Bold" Margin="10"
HorizontalAlignment="Center">XML Data Source Sample</TextBlock>
<ListBox
Width="265" Height="98" x:Name="lbox" Background="Honeydew" IsSynchronizedWithCurrentItem="True">
<ListBox.ItemsSource>
<Binding Source="{StaticResource InventoryData}"
XPath="*[#Stock='out'] | *[#Number>=8 or #Number=3]"/>
</ListBox.ItemsSource>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock FontSize="12" Foreground="Red">
<TextBlock.Text>
<Binding XPath="Title"/>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<StackPanel DataContext="{StaticResource InventoryData}">
<TextBlock Text="{Binding XPath=Book/Title}"/>
<TextBox Margin="5,31,98,10" x:Name="textBoxMainDetail" Text="{Binding XPath=Book/Summary}" />
</StackPanel>
</StackPanel>
</Grid>
You could bind like this:
<TextBox Text="{Binding ElementName=lbox, Path=SelectedItem[Title].InnerText}" />
SelectedItem is an XmlElement.
EDIT: Here is a bit of sample code how to access the data of the XmlDataProvider in code behind and apply it as DataContent of a TextBox.
Change the TextBox.Text binding like this:
<TextBox x:Name="textBoxMainDetail" Text="{Binding Path=[Title].InnerText}" />
In code behind get the XML data from the XmlDataProvider and set the DataContext of the TextBox:
XmlDataProvider dataProvider = (XmlDataProvider)stackPanel.Resources["InventoryData"];
XmlElement books = (XmlElement)dataProvider.Document.SelectNodes(dataProvider.XPath)[0];
// set DataContext to an item from the child node collection
textBoxMainDetail.DataContext = books.ChildNodes[0];
Note that the StackPanel with the XmlDataProvider in its resource dictionary has now got a name. If this code shall run during application initialization (e.g. in Window constructor), the XmlDataProvider.IsAsynchronous property must be set to false.
You should now be able to change the DataContext to another indexed item of the books collection in a button click handler.
You need to set the SelectedValuePath as the 'Title' for your listbox. Then simply bind the your textBlock to the selectedValue of your listbox using elementName like this -
<ListBox Width="265" Height="98" x:Name="lbox" Background="Honeydew"
IsSynchronizedWithCurrentItem="True" SelectedValuePath="Title">
</ListBox>
<StackPanel DataContext="{StaticResource InventoryData}">
<TextBlock Text="{Binding Path=SelectedValue, ElementName=lbox}"/>
<TextBox Margin="5,31,98,10" x:Name="textBoxMainDetail" Text="{Binding XPath=Book/Summary}" />
</StackPanel>
</StackPanel>

Bind a generic list to a listbox and also use a datatemplate

I'm trying to implement something quite simple but I'm on my first steps in WPF and I'm having some problems. I have a class called Component which has a property called Vertices. Vertices is a generic List of type Point. What I want is to bind the vertices property to a listbox. This is easy by using this code in my XAML in the listbox declaration:
ItemsSource="{Binding Path=Component.Vertices, Mode=OneWay, Converter={StaticResource verticesconverter},UpdateSourceTrigger=PropertyChanged}"
The tricky part is when I try to create a datatemplate for the listbox. I want each row of the listbox to display a textbox with the values of the Vertex (Point.X, Point.Y) and a button to allow me to delete the item. Could you help me on the datatemplate definition. The code below doesn't work to bind the X,Y values into two separate textboxes. Could you point me on the mistake and why nothing is displayed in the textboxes?
<ListBox ItemsSource="{Binding Path=Component.Vertices, Mode=OneWay,UpdateSourceTrigger=PropertyChanged}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="0,10,0,0">
<TextBox Text="{Binding X}" MinWidth="35" MaxWidth="35"/>
<TextBox Text="{Binding Y}" MinWidth="35" MaxWidth="35"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
/ListBox>
Something like this:
<ListBox ... Grid.IsSharedSizeScope="True">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition SharedSizeGroup="A"/>
<ColumnDefinition SharedSizeGroup="B"/>
<ColumnDefinition SharedSizeGroup="C"/>
</Grid.ColumnDefinitions>
<Grid.Children>
<TextBlock Grid.Column="0" Text="{Binding X}" Margin="5"/>
<TextBlock Grid.Column="1" Text="{Binding Y}" Margin="5"/>
<Button Grid.Column="2" Tag="{Binding}" Margin="5" Click="Button_Click" Content="Remove"/>
</Grid.Children>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Event handler:
private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
{
Button senderB = (Button)sender;
Point pt = (Point)senderB.Tag;
Collection.Remove(pt);
}
Note: Your list in the GUI will not get updated unless your bound collection implements INotifyCollectionChanged (Standard-implementation you can use: ObservableCollection<T>)
Edit: Common binding-fail causes:
1. Bound source is not a public property -> make it one
2. Binding path is not absolute and there is no DataContext to start from
-> Set DataContext of your window in the constructor to itself (this) or...
-> Set ElementName in the Binding to the name of your window if that is where your property is
Edit2: If your collection consists of Vertices and if your Vertex class contains a point with the property-name Point you need to change the bindings to {Binding Point.X} and {Binding Point.Y}, post more code next time please.

Resources