<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.
Related
I have a view and ViewModel that are working perfectly. I have recently added an AutocompleteBox (found in the WPF Toolkit) which allows users to quickly look up an item.
My view is as such:
An ItemsControl containing my CollectionViewSource named People. Generating perfectly
An AutocompleteBox where the dropdown shows only the items containing the values the user is typing in the AutocompleteBox. Works well. If I type John, all of the people in my CollectionViewSource named People with the word John in the name appear in the dropdown.
My issue is: how do I filter my ItemsControl when the user selects the item he wishes to see from the Dropdown?
My code so far in XAML to bind the data:
<toolkit:AutoCompleteBox Height="25" Width="400"
Foreground="AliceBlue"
ItemsSource="{Binding People.View}"
ValueMemberPath="Name"
Text="{Binding Name}"
IsTextCompletionEnabled="True"
FilterMode="Contains"
Background="#303030">
<toolkit:AutoCompleteBox.ItemTemplate>
<DataTemplate>
<Grid Width="360" HorizontalAlignment="Left">
<StackPanel Orientation="Vertical" HorizontalAlignment="Left"
VerticalAlignment="Top" Width="300">
<TextBlock Text="{Binding Name}" FontWeight="SemiBold" Foreground="#25A0DA"
FontSize="14" Width="300"/>
<TextBlock Text="{Binding Status}" FontWeight="Normal" Foreground="White"
FontSize="10" Width="300"/>
</StackPanel>
</Grid>
</DataTemplate>
</toolkit:AutoCompleteBox.ItemTemplate>
</toolkit:AutoCompleteBox>
<ItemsControl x:Name="tStack" Grid.Column="0" Grid.Row="1"
ItemsSource="{Binding People.View}"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
BorderThickness="0.5">
</ItemsControl>
The itemsControl is styled and the format of the items inside it are also templated/styled but far too long and unconstructive to post here.
From the Name property setter in your viewmodel to which toolkit:AutoCompleteBox.Text is bound, you will have to filter the ObservableCollection backing your Collectionview i,e ItemsSource of your ItemsControl.
If you have your Collectionsource with you then you can have filter applied to it like below:
ICollectionView _peopleView = CollectionViewSource.GetDefaultView(peoples);
_peopleView .Filter = PeopleFilter
private bool PeopleFilter(object item)
{
People people= item as People;
return people.Name.Contains( _filterString ); //Here filter string will be your Name prperty value
}
From Setter of name property you will hav to call _peopleView .Refresh(); to apply the filter
Thanks
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
I have an ItemsControl bound to a list of objects.
It basically displays a list of bound properties on screen with a textbox and button next to each one to allow you to add additional information to each database field.
In the onclick of the button I need to take the string in the textbox and store it in the object for that item. The XAML looks a bit like this
<ItemsControl x:Name="ListDatabaseFields" ItemsSource="{Binding Path=SelectedImport.ColumnMappings}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<StackPanel>
<TextBlock Text="{Binding DatabaseColumn.Name}" TextWrapping="Wrap" Grid.Column="0"/>
<TextBox Name="txtNewFileField" Width="100"/>
<Button Name="Add" Content="Add File Field" Style="{StaticResource LinkButton}" Width="50" Click="Add_Click"/>
</StackPanel>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Whats the best way in the XAML to access the ColumnMapping the itemcontrol is bound to for that item and change its file field property.
I'm not sure if i understood your question correctly, please clarify if this is not what you are looking for.
I have adapted this to my test application, my DataTemplate looks like this:
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}"/>
<TextBox MinWidth="100" Name="tbNewName"/>
<Button MinWidth="100"
Tag="{x:Reference tbNewName}" Click="ButtonNewName_Click"
Content="Do Stuff"/>
</StackPanel>
</DataTemplate>
Notice the Button.Tag which references the TextBox, i can use it in the handler like this:
private void ButtonNewName_Click(object sender, RoutedEventArgs e)
{
Employee emp = (sender as FrameworkElement).DataContext as Employee;
TextBox tbNewName = (sender as FrameworkElement).Tag as TextBox;
emp.Name = tbNewName.Text;
}
The DataContext is inherited, so the sender (the Button) contains the data-item, in your case a ColumnMapping, the Tag gives me the TextBox and that is all i need for changing a property.
If you need to reference more controls you could create an array in the Tag.
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.
The XAML below is basically trying to make a list of Buttons (rendered from the Name property of objects in the Views collection in the current DataContext.
When I click on a button the CurrentItem property of CollectionViewSource should change and the associated View should be displayed in a content presenter.
OK. If I click in the ListBox in the XAML below it works exactly as desired.
But, If I click a button in the UniformGrid (created by the items control) the CurrentItem property is not updated.
How do I get the CurrentItem to be updated when an item is selected in the ItemsControl?
Thanks
<UserControl x:Class="Pos.Features.Reservation.ReservationView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:product="clr-namespace:Pos.Features.ProductBrowser"
xmlns:activity="clr-namespace:Pos.Features.ActivityBrowser"
xmlns:addbysku="clr-namespace:Pos.Features.AddBySku"
xmlns:client="clr-namespace:Pos.Features.ClientBrowser"
xmlns:notes="clr-namespace:Pos.Features.Notes"
xmlns:controls="clr-namespace:Pos.Views"
xmlns:res="clr-namespace:Pos.Core;assembly=Pos.Core"
Height="300" Width="300">
<UserControl.Resources>
<DataTemplate DataType="{x:Type product:ProductBrowserViewModel}">
<product:ProductBrowserView/>
</DataTemplate>
<DataTemplate DataType="{x:Type activity:ActivityBrowserViewModel}">
<activity:ActivityBrowserView/>
</DataTemplate>
<CollectionViewSource x:Name="x" x:Key="ViewsCollection" Source="{Binding Views}" />
</UserControl.Resources>
<StackPanel>
<ListBox Name="ListBoxMenu" Grid.Column="0" Margin="5" ItemsSource="{Binding Source={StaticResource ViewsCollection}}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" Padding="10"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<ContentControl Grid.Column="1" Content="{Binding ElementName=ListBoxMenu, Path=SelectedItem}"/>
<ItemsControl Grid.Column="2" Name="ViewList" ItemsSource="{Binding Source={StaticResource ViewsCollection}}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button>
<TextBlock Text="{Binding Path=Name}" Name="txtButtonLabel" VerticalAlignment="Center" HorizontalAlignment="Center" Foreground="Black"/>
</Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Rows="1" Columns="{Binding Views.Count}"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
<ContentControl Grid.Column="3" Content="{Binding Source={StaticResource ViewsCollection}, Path=CurrentItem}"/>
<Button Grid.Column="4" Click="Button_Click">dsadsd</Button>
</StackPanel>
</UserControl>
Your button does nothing. Usually your ViewModel would have an ICommand called Select (or something similar) that the Button would be bound against
Command="{Binding Select, ElementName="root"}"
and you'd pass the instance to the ICommand that you'd like to select
CommandParameter="{Binding}"
It would look something like this (c#/XAML like pseudocode):
public class MyModel { public string Name {get;set;} }
public class MyViewModel
{
public ObservableCollection<MyModel> Models {get;set;}
public ICommand Select {get;set;}
/* configure Models and Select etc */
}
<UserControl DataContext="{StaticResource MyViewModelInstance}" x:Name="root">
<ItemsControl ItemsSource="{Binding Models}">
<ItemsControl.ItemTemplate>
<ItemsPanelTemplate>
<Button Text="{Binding Name}"
Command="{Binding Select, ElementName="root"}"
CommandParameter="{Binding}"/>
</ItemsPanelTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</UserControl>
The ItemsControl binds to Models, so each MyModel in Models gets a button. The button text is bound to the property Name. The button command is bound to the Select property in the ViewModel. When the button is pressed, it calls the ICommand, sending in the instance of MyModel that the button is bound against.
Please do note that using ViewModels within a UserControl is a code smell. UserControls should appear to users as all other controls--they should have bindable public properties which are bound to the user's ViewModel, not yours. You then bind to the values of these properties within the UserControl. For this example, you would have an ItemsSource property defined on your UserControl, and the ItemsControl would bind to this property rather than a ViewModel directly.
I think you have to do it manually in code-behind.
XAML
<Button Click="ViewListButton_Click">
<TextBlock Text="{Binding Path=Name}" Name="txtButtonLabel" VerticalAlignment="Center" HorizontalAlignment="Center" Foreground="Black"/>
</Button>
Code-behind
private void ViewListButton_Click(object sender, RoutedEventArgs e)
{
Button button = sender as Button;
ICollectionView view = CollectionViewSource.GetDefaultView(ViewList.ItemsSource);
view.MoveCurrentTo(button.DataContext);
}
If you're using the MVVM pattern and/or you don't want to use code-behind, you could bind the button's Command to a command in your ViewModel, as suggested by Will