Find an element in DataTemplate applied to TabItem - wpf

I got a problem trying to find an element declared in DataTemplate, that after was applied like a ContentTemplate to TabItem object.
I saw that there is already some solutions in regard of this problem, but no one of them actually works in my case, and I would like to understand why (obviously I make mistake in some place)
Here is a sample code:
<DataTemplate x:Key="TabItemDataTemplate">
<Grid HorizontalAlignment="Stretch"
VerticalAlignment="Stretch" Name="templateGrid">
<Grid.RowDefinitions>
<RowDefinition Height="6.0*"> </RowDefinition>
<RowDefinition Height="6" ></RowDefinition>
<RowDefinition Height="6.0*" ></RowDefinition>
<RowDefinition Height="*" ></RowDefinition>
</Grid.RowDefinitions>
<ListView x:Name="repoView" Grid.Row="0"
VerticalAlignment="Stretch"
ItemsSource="{Binding Source={StaticResource DataProviderForListView}}">
<GridView>
<GridViewColumn Header="State"
DisplayMemberBinding="{Binding Path=RepositoryItemState}"/>
<GridViewColumn Header="Working Copy Rev num."
DisplayMemberBinding="{Binding Path=WCRevision}"/>
<GridViewColumn Header="Repository Rev num."
DisplayMemberBinding="{Binding Path=RepoRevision}"/>
<GridViewColumn Header="User"
DisplayMemberBinding="{Binding Path=Account}"/>
<GridViewColumn Header="Item"
DisplayMemberBinding="{Binding Path=ItemName}"/>
</GridView>
</ListView>
<GridSplitter x:Name="gridSplitter" Grid.Row="1"
ResizeDirection="Rows" Background="Gray"
Height="4" HorizontalAlignment="Stretch"
Style="{StaticResource gridSplitterStyle}"/>
<RichTextBox x:Name="rowView" Grid.Row="2"
BorderBrush="Bisque" VerticalAlignment="Stretch"
IsReadOnly="True" Background="YellowGreen"
FontFamily="Comic Sans Serif"/>
<ToggleButton x:Name="rbWorkingCopy"
Template="{StaticResource ToggleButtonControlTemplate}"
Grid.Row="3" Width="100" Height="22"
Content="{StaticResource WorkingCopyTitle}"
HorizontalAlignment="Left" VerticalAlignment="Bottom"
Command="repoManager:AppCommands.GetWorkingCopyInfoCommand" />
<ToggleButton x:Name="rbRepository"
Template="{StaticResource ToggleButtonControlTemplate}"
Grid.Row="3" Width="100" Height="22"
Content="{StaticResource RepositoryTitle}"
HorizontalAlignment="Left"
VerticalAlignment="Bottom" Margin="120,0,0,0"
Command="repoManager:AppCommands.GetRepoInfoCommand" />
<ProgressBar x:Name="checkRepositoryProgress" Grid.Row="3"
Width="220" Height="22" HorizontalAlignment="Right"
VerticalAlignment="Bottom" Margin="250,0,10,0"
IsIndeterminate="True"
IsEnabled="{Binding repoManager:ExecutingCommand}" />
</Grid>
</DataTemplate>
This code is porgrammatically applied to the given TabItem object in following way :
this.ContentTemplate = FindResource("TabItemDataTemplate") as DataTemplate;
After I need access to the ListView element declared in DataTemplate, so I execute the codes found around in internet, and also on this site. Here is a short example:
/* Getting the ContentPresenter of myListBoxItem*/
ContentPresenter myContentPresenter =
FindVisualChild<ContentPresenter>(this);
// this.GetVisualChild(0)
/* Finding textBlock from the DataTemplate that is set on that ContentPresenter*/
DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;
ListView repoListView = (ListView)myDataTemplate.FindName("repoView",
myContentPresenter);
Problem1: In this case ContentTemplate of ContentPresenter is Null, so code execution crashes.
Prolem2: Ok, I think, may be I need to navigate throw TabItem content directly, so the code becomes, more or less:
/* Getting the ContentPresenter of myListBoxItem*/
ContentPresenter myContentPresenter =
FindVisualChild<ContentPresenter>(this);
// this.GetVisualChild(0)
/* Finding textBlock from the DataTemplate that is set on that ContentPresenter*/
DataTemplate myDataTemplate = this.ContentTemplate;
ListView repoListView = (ListView)myDataTemplate.FindName("repoView",
myContentPresenter);
this is TabItem object. But the strage things, that the ContentTemplate of this is completely different from that one assigned above. I'm sure that I missed something somewhere, can you help me to figure out the problem ?
Thank you.

You don't want to use any of the template properties of the TabItem, since those are used to create the actual controls, rather than storing them. You should be able to search the visual tree for the ListView directly, rather than going through the DataTemplate.

Ok, here we come :)
I resolve the problem, in not very nice way, but it seems that works correctly.
As I mentioned above I used LoadContent method and it returns me the ListView object, but by the way it wasn't the ListView that UI actually uses. So to resolve that problem I add static property to hold my REAL ListView object (static as I have single DataTemplate that contains ListView shared across multiple TabItems, so the ListView shared too) and add event handler to my DataTemplate -> Loaded. Catching this event, that in my case raises only ones in lifetime of application, in RoutedEvent's OriginalSource I got the REAL ListView object that WPF engine uses for rendering on UI.
Hope my solution will help someone.
Thank you all.

Simply, if you have a DataGrid, and a TemplateColumn which contains a data template, you can use the following code sample:
<DataGridTemplateColumn x:Name="photoPathColumn" Header="{x:Static resx:FrmResource.Photo}" Width="Auto">
<DataGridTemplateColumn.CellEditingTemplate x:Uid="keyelm">
<DataTemplate x:Name="dodo">
<StackPanel Orientation="Horizontal" Height="Auto">
<TextBlock x:Name="photo" x:Uid="imageFile" Text="{Binding Path=PhotoPath}"></TextBlock>
<Button x:Name="Browse" Content="..." Click="Browse_Click"></Button>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
TextBlock tBlock = (TextBlok)photoPathColumn.CellEditingTemplate.FindName(
"photo",
photoPathColumn.GetCellContent(CustomersDataGrid.CurrentItem));
Where photo is the name of text block
Where photoPathColumn is the DataGrid's TemplateColumn.

Related

Bizarre bug when pasting to DataGridTemplateColumn

I have a DataGridTemplateColumn than contains a UserControl:
<DataGridTemplateColumn Header="Projection"
SortMemberPath="SelectedItem"
ClipboardContentBinding="{Binding ProjectionMethod.Value, Mode=TwoWay}"
>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<local:DataGridComboBoxCellControl DataContext="{Binding}"
SelectedItem="{Binding ProjectionMethod.Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
ItemsSource="{Binding ProjectionMethodsTextWrapper, Mode=OneWay}"
ErrorMessage="{Binding ProjectionMethod.ErrorMessage, Mode=OneWay}">
</local:DataGridComboBoxCellControl>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
The UserControl bindings are done with DependencyProperties I set up inside the UserControl definition.
For the most part, the control works fine. But when pasting, even though the contents visually appear to be pasted, the cell never commits the paste contents to ProjectionMethod.Value (even though it is set as the ClipboardContentBinding). Debugging reveals that the setter of ProjectionMethod.Value is never even called.
Even more strangely, the constructor of the UserControl is being called during paste. I have no idea why this is occurring. I am pasting to existing cells, no new rows are being created. I was assuming the ClipboardContentBinding routes straight to the underlying property ProjectionMethod.Value. Why the paste command is even bothering with UI controls is a mystery to me.
It seems this problem might require someone with a fairly deep understanding of WPF.
(Here is the current xaml of the UserControl. Right now it's basically a TextBlock and a ComboBox with a few other controls for displaying errors. Any lines with ElementName=parentControl are bindings to dependency properties. Both the TextBlock and ComboBox bind to the same SelectedItem DP.
<UserControl x:Class="DataGridComboBoxCellControl"
x:Name="parentControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:MyProject"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
<local:MyStringToThicknessConverter x:Key="PopToOne" PopString="1" EmptyString="0"/>
<local:MyStringToVisibilityConverter x:Key="PopToVis" PopString="Visible" EmptyString="Collapsed"/>
</UserControl.Resources>
<Grid ToolTip="{Binding ElementName=parentControl, Path=ErrorMessage, Mode=OneWay}"
IsEnabled="{Binding IsProjectionEnabled}" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Border Grid.ColumnSpan="3" BorderThickness="{Binding ElementName=parentControl, Path=ErrorMessage, Mode=OneWay, Converter={StaticResource PopToOne}}"
BorderBrush="Red"/>
<Control Grid.Column="0"
Margin="1,0"
Template="{DynamicResource local:MyStyleRef, ResourceKey=errorGrid}"
Visibility="{Binding ElementName=parentControl, Path=ErrorMessage, Mode=OneWay, Converter={StaticResource PopToVis}}"/>
<TextBlock Grid.Column="1" Text="{Binding ElementName=parentControl, Path=SelectedItem, Mode=OneWay}" VerticalAlignment="Center"/>
<ComboBox Grid.Column="2"
Style="{DynamicResource local:MyStyleRef, ResourceKey=noText_ComboBoxStyle}"
ItemsSource="{Binding ElementName=parentControl, Path=ItemsSource, Mode=OneWay}"
SelectedItem="{Binding ElementName=parentControl, Path=SelectedItem}" />
</Grid>
</UserControl>
Update
I have now tried getting rid of the UserControl altogether and dumping its xaml code directly into the DataTemplate of the TemplateColumn - the same issue more or less. Visually the paste appears to execute, but the setter of ProjectionMethod.Value is never called and the viewmodel is therefore never updated. I am using the OnPastingCellClipboardContent command to paste.
I think I figured it out. I set the update trigger for the clipboard paste to PropertyChanged:
ClipboardContentBinding="{Binding ProjectionMethod.Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
And now the value is being committed immediately when pasting. I don't know what the default behavior is supposed to be, but before the paste values were never committed, even after row leave. And still not sure why the UserControl's constructor was being called.

TextBlock1 is not declared. It may be inaccessible due to its protection level

As silly as this sounds I'm a little stumped at this one. Here's my XAML in a Win Phone 8 App:
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel Grid.Row="0" Margin="12,17,0,28">
<TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock Text="Page" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<phone:LongListSelector x:Name="MainLongListSelector" Margin="0,0,-12,0" ItemsSource="{Binding Items}" SelectionChanged="MainLongListSelector_SelectionChanged">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,17">
<TextBlock x:Name="TextBlock1" HorizontalAlignment="Left" TextWrapping="Wrap" VerticalAlignment="Top"/>
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
</Grid>
</Grid>
I've searched around but I don't know why I can't write code against the TextBlock1 control in code behind. When I type TextBlock1.Text= .... I get the error TextBlock1 is not declared. It may be inaccessible due to its protection level. But I can't see how it is private?
All I'm trying to do is add a textblock, assign some content to it, and then that selected value is passed across another page to perform relevant action.
In addition as soon as I remove it outside of the PhoneListSelector I can access it.
TextBlock1 is defined inside an ItemTemplate, anything defined a Template cannot be access directly as it will be created on runtime by the control.
You probably need to do binding on the TextBlock if you want to manipulate anything that the LongListSelector's DataContext has.
<phone:LongListSelector x:Name="MainLongListSelector" Margin="0,0,-12,0" ItemsSource="{Binding Items}" SelectionChanged="MainLongListSelector_SelectionChanged">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,17">
<TextBlock x:Name="TextBlock1" Text="{Binding Content"} HorizontalAlignment="Left" TextWrapping="Wrap" VerticalAlignment="Top"/>
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
MainLongListSelector.DataContext = new List<TestViewModel>();
public class TestViewModel : INotifyPropertyChanged
{
//Assuming you've implemented the interface
private string _content;
public string Content { get { return _content; } { set { _content = value; NotifyOfPropertyChanged("Content"); } }
}
From here, you can try to access the selected value content and pass that to the next page.
var selectedItem = MainLongListSelector.SelectedItem as TestViewModel;
GoToNextPage(selectedItem.Content);
I strongly suggest to read MVVM design pattern and everything should be easy for you to implement, always remember UI is not DATA it's responsibility is only to show something that is passed through the ViewModel.

ObservableCollection doesn't reflect changes in the DataGrid

I have implemented a DataGrid that way:
<DataGrid
x:Name="MyDataGridFilter"
ItemsSource="{Binding}"
IsSynchronizedWithCurrentItem="True"
AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn
x:Name="FilterTextCol01">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBox
Grid.Column="0"
IsHitTestVisible="True"
Text="{Binding Path=FilterTextCol01}" />
<CheckBox
Grid.Column="1"
x:Name="FilterAktivTextCol01"
IsHitTestVisible="True"
IsChecked="{Binding Path=FilterAktivTextCol01}"/>
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
The binding in the Code goes this way:
FilterItemsList = new ObservableCollection<DataGridFilterEntity>();
MyDataGridFilter.DataContext = FilterItemsList;
(it is shorted)
FilterItemsList is implemented as an INotifyPropertyChanged clas:
public class DataGridFilterEntity : INotifyPropertyChanged
With the member FilterTextCol01 (of course):
public string FilterTextCol01
{
get { return _FilterTextCol01; }
set
{
_FilterTextCol01 = value;
Changed("FilterTextCol01");
}
}
Everything works fine. When I change the FilterItemsList the DataGrid refelcts these changes.
But when I make some changes in the UI (in the DataGrid) it isn't reflected by the ObservableCollection (FilterItemsList).
I searched and tried some hours but did not find any solution.
Does anyone know how to solve this?
Thank you!
You need TwoWay binding.
For example,
<TextBox
Grid.Column="0"
IsHitTestVisible="True"
Text="{Binding Path=FilterTextCol01, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
<CheckBox
Grid.Column="1"
x:Name="FilterAktivTextCol01"
IsHitTestVisible="True"
IsChecked="{Binding Path=FilterAktivTextCol01, Mode=TwoWay}"/>
What kind of changes are you doing to the GUI? Are you updating the Text of the TextBox and checking the CheckBox?
If so the same example works in my case. I receive the updated text and checked boolean back in my model when I focus off the textbox or checkbox.

ListBox inside ListBox, how do I know which button is clicked?

I have two ListBoxes, one inside another. And both ListBoxes will have items dynamically added into them upon user request.
Each time a button (not shown in the below code snippet) is clicked, a new item is added to the listbox. Each new item includes a new listbox and others.
And I have buttons inside the inner listbox, one for each list item of the inner listbox.
With DataContext, I can find the data binded to the inner list item, and make changes to it, so that changes are reflected on the proper list item.
However, I also need to make changes to the data binded to the outer list item, which corresponds to the button. How can I know which one it is?
I have came up with a solution, which I believe it not elegant enough. By making changes to the model, I can have each inner data holds a reference to the outer data, so that I can find the data binded to the outer list item. This doesn't seem like a proper solution though. Do you have any suggestions?
Below is code snippet of the xaml. I've simplified it, hope it's easy to understand. I feel you don't have to read the whole code.
<ListBox Name="QuestionsListBox" HorizontalAlignment="Stretch" ItemContainerStyle="{StaticResource ListItem}" >
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBox Text="{Binding Question, Mode=TwoWay}" Grid.Row="0" HorizontalAlignment="Stretch" TextWrapping="Wrap"/>
<ListBox Name="ChoicesListBox" ItemsSource="{Binding Choices}" Grid.Row="1" HorizontalAlignment="Stretch" ItemContainerStyle="{StaticResource ListItem}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Button Grid.Column="0" Click="ChoiceAddButton_Click" Height="72" Width="72" HorizontalAlignment="Left" BorderBrush="Transparent">
<Button.Background>
<ImageBrush ImageSource="/Images/choices.add.png" Stretch="Fill" />
</Button.Background>
</Button>
<TextBox Text="{Binding Value, Mode=TwoWay}" HorizontalAlignment="Stretch" Grid.Column="1" Margin="-20,0" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Why not just use QuestionsListBox.DataContext inside ChoiceAddButton_Click directly? You have a direct way to reference the outer ListBox from your code behind since you've given it a name, and DataContext is an accessible property.
private void ChoiceAddButton_Click(object sender, RoutedEventArgs e)
{
...
var outerLBDataContext= QuestionsListBox.DataContext;
...
}
This works fine for me in a demo solution using your provided XAML.
Edit 2:
Sorry, wasn't thinking. The Button's DataContext will be a Choice, not the Choices collection.
Your inner ListBox's DataContext is not a Question, it's Choices. Your outer TextBox has Question.Question as its DataContext. Binding Text or ItemsSource makes the DataContext point to the binding target. Here is a bit of tricky XAML to sneak in a DataContext reference.
Add an ElementName to your outer TextBox:
<TextBox Text="{Binding Question, Mode=TwoWay}" Grid.Row="0" HorizontalAlignment="Stretch" TextWrapping="Wrap" ElementName="questionTextBox"/>
Now, add a hidden TextBlock inside your inner ListBox:
<ListBox Name="ChoicesListBox" ItemsSource="{Binding Choices}" Grid.Row="1" HorizontalAlignment="Stretch" ItemContainerStyle="{StaticResource ListItem}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Button Grid.Column="0" Click="ChoiceAddButton_Click" Height="72" Width="72" HorizontalAlignment="Left" BorderBrush="Transparent">
<Button.Background>
<ImageBrush ImageSource="/Images/choices.add.png" Stretch="Fill" />
</Button.Background>
</Button>
<TextBox Text="{Binding Value, Mode=TwoWay}" HorizontalAlignment="Stretch" Grid.Column="1" Margin="-20,0" />
<TextBlock Name="hiddenTextBlock" Visibility="Collapsed" DataContext="{Binding ElementName=questionTextBox, Path=DataContext}"
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Finally, inside your event handler, you can navigate around the tree to get that reference:
private void ChoiceAddButton_Click(object sender, RoutedEventArgs e)
{
Button btn = sender as Button;
if(btn == null) return; //won't happen when this method handles the event
Grid g = btn.Parent as Grid;
if(g!=null) // also unlikely to fail
{
TextBlock tb = g.FindName("hiddenTextBlock") as TextBlock;
if(tb!=null) // also unlikely to fail, but never hurts to be cautious
{
var currentQuestion = tb.DataContext;
// now you've got the DC you want
}
}
}
I'd like to note that this isn't really an elegant solution. It is an all UI solution, however, which could be a useful thing. But better design would be to include Parent references in your Choice and ChoiceList (or whatever they're called) classes and use that. Then it would be as simple as calling btn.DataContext.Parent.Parent with appropriate type conversions. This way your code becomes easier to read and maintain.
You could add an event to your inner model that your containing datamodel subscribes to before adding it to the 'Choices' collection and pass the relevant information that way.
Is this necessary to use the Button control in your solution ??
If not fixed, then you can use the "Image control" as specified below <Image Source="/Images/choices.add.png" Height="72" Width="72" HorizontalAlignment="Left" Stretch="Fill"/>
If you use the Image control then in combination with this you can add the selection changed event to inner list box ( ChoicesListBox). Then in the Handler you can get the item selected as it comes as parameter with the selection changed event(SelectionChangedEventArgs).
Modify the List box and add the Selection changed event handler as below
<ListBox Name="ChoicesListBox" ItemsSource="{Binding Choices}" Grid.Row="1" HorizontalAlignment="Stretch" ItemContainerStyle="{StaticResource ListItem}" SelectionChanged="Items_SelectionChanged">
in page.xaml.cs you can add the handler and access the item as follows
private void Items_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems[0] != null)
{
//Please use the casting to the Choices items type to make use.
var temp = (ChoicesItemViewModel)e.AddedItems[0];
}
}

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