Access Datagrid row on TemplateColumn button click - silverlight

I am implementing a file upload tool using Silverlight. In this I can browse for files and when I select a file then it is bound to a datagrid. In the datagrid I have a template column with a button to delete the particular item from the datagrid and ItemSource of the datagrid which is a List<>.
I have a class UploadedFiles as below.
public class UploadedFiles
{
public FileInfo FileInf{get;set;}
public int UniqueID{get;set;}
public string FileName{get;set;}
public string FileExtension{get;set;}
public long FileSize{get;set;}
}
I am using a datagrid with a templatecolumn like below with ItemSource set as List<UploadedFiles>
<data:DataGridTemplateColumn Width="100">
<data:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Click="btn_Click" Content="Del" Width="45"/>
</DataTemplate>
</data:DataGridTemplateColumn.CellTemplate>
</data:DataGridTemplateColumn>
and the button click event handler is
private void btn_Click(object sender, System.Windows.RoutedEventArgs e)
{
/* I need to access the particular list item based on the datagrid
row in which the clicked button resides.*/
}
I need to access the particular list item based on the datagrid row in which the clicked button resides and remove the item from the List<UploadedFiles> and rebind the datagrid.
Thanks

Two things to look at here:
Firstly, to get the individual UploadedFiles object, cast the sender to a Button (or FrameworkElement) and access the DataContext property. The DataContext will be the UploadedFiles row (you will need to cast again from object).
Secondly, rather than removing the item from the list and rebinding, have you considered using an ObservableCollection instead? If you use that, removing the row will automatically remove it from the DataGrid without needing you to rebind.
private void btn_Click(object sender, System.Windows.RoutedEventArgs e)
{
var uploadedFiles = (UploadedFiles)((FrameworkElement)sender).DataContext;
//access collection and remove element
}

Related

How to scroll to a given row when WPF DataGrid is loaded

I display a few thousand rows in a WPF DataGrid, but would like to automatically scroll to a specific row when it is loaded (and later also add a button to scroll to this specific row). Is it possible to achieve it via data binding or from a view model property?
Of course, I've already browsed the Internet, but could not find any corresponding property.. For exemple, SelectedCells only has a get accessor (but I don't think it would have scrolled whatsoever anyway). I don't think that the other properties, such as SelectedItem helps.
Thanks for any insights :-)
There are two options: scroll to a row without selecting it and scroll to a row and select it.
Scroll to row without selecting it
This solution works for any DataGrid.SelectionUnit value (cell or row based selection).
You set the row from a property in your view model, which binds to DataGrid.CurrentItem.
Scrolling must be handled by the DataGrid by handling the DataGrid.CurrentCellChanged event.
View model (must implement INotifyPropertyChanged)
object currentRow = this.DataSource[currentRowIndex];
this.CurrentRow = currentRow;
View.xaml
<DataGrid ItemsSource="{Binding DataSource}"
CurrentItem="{Binding CurrentRow}"
CurrentCellChanged="DataGrid_OnCurrentCellChanged" />
View.xaml.cs
private void DataGrid_OnCurrentCellChanged(object sender, EventArgs eventArgs)
{
var dataGrid = sender as DataGrid;
dataGrid.ScrollIntoView(dataGrid.CurrentItem);
}
Scroll to row by selecting it
This solution works only for DataGrid.SelectionUnit values DataGridSelectionUnit.FullRow or DataGridSelectionUnit.CellOrRowHeader (not cell-only based selection - cell-only solution must completely handle selection and scroll in view).
You set the selected row from a property in your view model, which binds to DataGrid.SelectedItem.
Scrolling must be handled by the DataGrid by handling the DataGrid.SelectionChanged event.
View model (must implement INotifyPropertyChanged)
object selectedRow = this.DataSource[currentRowIndex];
this.SelectedRow = selectedRow;
View.xaml
<DataGrid ItemsSource="{Binding DataSource}"
SelecetedItem="{Binding SelectedRow}"
SelectionChanged="DataGrid_OnCurrentCellChanged" />
View.xaml.cs
private void DataGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs eventArgs)
{
var dataGrid = sender as DataGrid;
dataGrid.ScrollIntoView(dataGrid.SelectedItem);
}

TextBlock binding to selected DataGrid Element

Does anyone know how to dynamically set the ElementName for textblock.text binding?
I have two Datagrids that have the same information but the second DataGrid is just a filter of the same datasource, but what I want is to bind text of a textblock to the selected item depending if the item was clicked in the main datagrid or the secondary datagrid.
I have the below code to bind the textblock to one datagrid but I would also like the same to happen if the user clicked an item in the secondDataGrid.
Is this possible?
<TextBlock Margin="29,0" Text="{Binding SelectedItem.Name, ElementName=MainDataGrid}"
It is possible, though I don't think this is the proper solution.
You can handle one of the DataGrids' events in the code-behind, where in the handler you can write the following code:
BindingOperations.SetBinding(textBlock, TextBlock.TextProperty,
new Binding("SelectedItem.Name")
{
ElementName = "DataGrid1"
});
Basically you reset the Binding on the TextBlock's Text property with this code, where:
textBlock is the name of your TextBlock;
with TextBlock.TextProperty you define that you want to work with the Text property on the TextBlock;
The third paramter is the new Binding itself. The constructor takes the Path of the Binding and then in the "body" I set the ElementName.
If DataGrid1 fires the event you set the ElementName to that DataGrid's name, if DataGrid2 fires the event then you set the ElementName to the second DataGrid's name.
SelectionChanged can be a good event to handle on both DataGrid, but if you want the TextBlock to update when you selected and element in the first then select another one in the second and then click back to the first element to update then you need to handle the GotFocus event as well.
Play a little bit with it and you will see what I mean.
My working example:
private void SetBindingOnTextBlock(string elementName)
{
BindingOperations.SetBinding(textBlock, TextBlock.TextProperty, new Binding("SelectedItem.Name")
{
ElementName = elementName
});
}
private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
SetBindingOnTextBlock("DataGrid1");
}
private void DataGrid_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
SetBindingOnTextBlock("DataGrid2");
}
private void DataGrid1_GotFocus(object sender, RoutedEventArgs e)
{
SetBindingOnTextBlock("DataGrid1");
}
private void DataGrid2_GotFocus(object sender, RoutedEventArgs e)
{
SetBindingOnTextBlock("DataGrid2");
}
UPDATE 1:
Set
IsSynchronizedWithCurrentItem="True"
on the DataGrids and it may solve your problem if ItemsSources are the same. (Not sure if this is what #dkozl meant) Originally I assumed that they are different.

Binding Button.IsEnabled to position of current in CollectionView

I am trying to bind the IsEnabled property of a button to properties of the window's CollectionViewSource. I am doing this to implement First/Previous/Next/Last buttons and want the First and Previous to be disabled when the view is on the first item etc.
I have the collection view source set up, UI controls binding to it correctly, with access to its view in code so the click event handlers work fine in navigating through the view.
<CollectionViewSource x:Key="cvMain" />
The DockPanel is the root element of the window
<DockPanel DataContext="{StaticResource cvMain}">
FoJobs is an observable collection, cvJobs is a CollectionView that I use in the button's click handler
private void Window_Loaded(object sender, RoutedEventArgs e) {
((CollectionViewSource)Resources["cvMain"]).Source = FoJobs;
cvJobs = (CollectionView)((CollectionViewSource)Resources["cvMain"]).View;
}
I have tried this but get a binding error "BindingExpression path error: '' property not found on 'object' ''ListCollectionView'"
<Button Name="cbFirst" Click="cbMove_Click" IsEnabled="{Binding Source={StaticResource cvMain}, Converter={StaticResource CurrPos2BoolConverter}}" />
I am trying to do with a converter first but figure a style with triggers would be more efficient, but cant get access to the collection view. Even though the underlying datacontext is set to a collection view source, the binding is passed to the converter as the view's source (if I dont explicity set the binding's Source, as above), which has no currency properties (CurrentPosition, Count etc).
Any help would be greatly appreciated.
Why don't you use a RoutedCommand for this(even if you don't use MVVM that is)?
say something like:
<Button x:Name="nextButton"
Command="{x:Static local:MainWindow.nextButtonCommand}"
Content="Next Button" />
and in your code-behind:
public static RoutedCommand nextButtonCommand = new RoutedCommand();
public MainWindow() {
InitializeComponent();
CommandBinding customCommandBinding = new CommandBinding(
nextButtonCommand, ExecuteNextButton, CanExecuteNextButton);
nextButton.CommandBindings.Add(customCommandBinding); // You can attach it to a top level element if you wish say the window itself
}
private void CanExecuteNextButton(object sender, CanExecuteRoutedEventArgs e) {
e.CanExecute = /* Set to true or false based on if you want button enabled or not */
}
private void ExecuteNextButton(object sender, ExecutedRoutedEventArgs e) {
/* Move code from your next button click handler in here */
}
You can also apply one of the suggestions from Explicitly raise CanExecuteChanged() to manually re-evaluate Button.isEnabled state.
This way your encapsulating logic relating to the button in one area.

How to have a button in a datagrid template that will remove the item when clicked

I would like to use a datatemplate for my datagrid columns and have a button for each item. I would like the item to be removed if the user clicks the button. I am using the MVVM pattern. How would I accomplish this?
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Width="50" Content="Remove" Command="{Binding RemoveItemCommand}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
public class ItemViewModel
{
public ItemViewModel()
{
RemoveCommand = new MyCommand(Remove);
}
public event EventHandler ItemRemoved;
public ICommand RemoveCommand { get; private set; }
private void Remove()
{
// Whatever it takes to remove item from your data store
service.Remove(this.Data);
var removeItem = ItemRemoved;
if (removeItem != null)
removeItem(this, EventArgs.Empty);
}
}
public class ListViewModel
{
public ListViewModel(IEnumerable<ItemViewModel> items)
{
ItemVMs=new ObservableCollection<ItemViewModel>(items);
foreach (var item in ItemVMs)
item.ItemRemoved += RemoveSelectedItem;
}
public ObservableCollection<ItemViewModel> ItemVMs { get; private set; }
private void RemoveSelectedItem(object sender, EventArgs e)
{
var item = sender as ItemViewModel;
item.ItemRemoved -= RemoveSelectedItem;
ItemVMs.Remove(item);
}
}
Each item's RemoveCommand would be bound to its button in your DataGrid. It sounds like you already have that part done. Make the ListViewModel's ItemVMs property the data source for your DataGrid.
The View is responsible for this. You can simply use codebehind to control the visibility of UI elements in response to user actions in the UI.
Sometimes, it is better to be practical than be rigidly dogmatic.
Well, now that you have edited your question, it becomes a completely different matter.
Your DataGrid should be bound to a collection of items.
Your button should be bound to a command on the ViewModel, and the CommandParameter should be the Model that particular row is bound to.
<DataTemplate>
<Button Content="Remove"
Command="{Binding DataContext.RemoveItemCommand,
ElementName=theWindow}"
CommandParameter="{Binding}" />
</DataTemplate>
Note some important things here. We need, from within the template, to bind to an ICommand on the ViewModel. The ViewModel is the DataContext of the Window. In this example, the window is named 'theWindow' (x:Name="theWindow"). Since the source of the Binding is the window, the Path must point to the ViewModel in the DataContext property on that Window.
We pass the current Model the DataGrid row is bound to into the command. This way, it is triival to remove it from the collection in the ViewModel.
public ObservableCollection<Model> Items {get;set;}
public ICommand RemoveItemCommand {get;set;}
// this method is called when RemoveItemCommand.Execute is called!
public void Execute(object parameter)
{
Items.Remove(parameter as Model);
}
This assumes you're using one of the standard delegated ICommand implementations out there. You can see how this is trivial to implement, and since the collection is an observable one, once you click the button and the Model is removed, the DataGrid will be notified of the change in the collection and remove that row.
You're probably better off using the standard routed events on the Click event of the button instead of a Command. The click event will allow you to retrieve the information about what control was clicked, and then you can also easily retrieve the parent of the button, to delete that item.

Silverlight get selected row data in DataGrid

In my Silverlight application I have defined a datagrid with an template column containing a radio button as follows:
XAML:
<data:DataGrid x:Name="Grid1" Margin="8">
<data:DataGrid.Columns>
<data:DataGridTemplateColumn Header="RadioButtons">
<data:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<RadioButton x:Name="rdbIndataGrid" IsChecked="false" GroupName="myGroup" />
</DataTemplate>
</data:DataGridTemplateColumn.CellTemplate>
</data:DataGridTemplateColumn>
</data:DataGrid.Columns>
</data:DataGrid>
C#
public MainPage()
{
// Required to initialize variables
InitializeComponent();
string data = "1,2,3,4,5,6,7,8,9";
Grid1.ItemsSource = data.Split(',');
}
When a button is clicked I want to be able to:
a) Find out which radio button was selected.
b) Get the data from one of the cells in the grid which corresponds to the selected radio button.
Is there an easy way to do this? There doesnt seem to be a rows collection on the grid. Or do I have to bind it to a datasource and then check the data source?
Many thanks.
The way I'd prefer to do this would be to bind IsChecked to a property of objects assigned to the ItemsSource. But here I'll show you the hard way to do it
(Edit: Actually the following is over complicated for this scenario but I'll leave it here for now, see edits after)
First you need one of my VisualTreeEnumeration extension methods:-
public static class VisualTreeEnumeration
{
public static IEnumerable<DependencyObject> Ancestors(this DependencyObject root)
{
DependencyObject current = VisualTreeHelper.GetParent(root);
while (current != null)
{
yield return current;
current = VisualTreeHelper.GetParent(current);
}
}
}
Now in my testing I've just added a ListBox with the name lstOutput to my Xaml. Now add the following couple of event handlers to you UserControl :-
private void rdbIndataGrid_Checked(object sender, RoutedEventArgs e)
{
DataGridRow row = ((DependencyObject)sender).Ancestors().OfType<DataGridRow>().FirstOrDefault();
if (row != null)
lstOutput.Items.Add(String.Format("Checked: {0}", row.DataContext));
}
private void rdbIndataGrid_Unchecked(object sender, RoutedEventArgs e)
{
DataGridRow row = ((DependencyObject)sender).Ancestors().OfType<DataGridRow>().FirstOrDefault();
if (row != null)
lstOutput.Items.Add(String.Format("Unchecked: {0}", row.DataContext));
}
and finally tweak the Radio button Xaml like so:-
<RadioButton x:Name="rdbIndataGrid" IsChecked="false" GroupName="myGroup"
Checked="rdbIndataGrid_Checked" Unchecked="rdbIndataGrid_Unchecked" />
(One of the neat things about Xaml wiring up events is that it works even when the elements are part of a Template).
You'll note that in the event handlers I'm walking up the visual tree from the sending RadioButton to find the containing DataGridRow. The DataGridRow is the object that its DataContext set to the object being rendered by that row. In your own code you could cast the data context value to the correct type and from there access other data about the row.
Edit
Actually in most ordinary cases you don't need to hunt down the owning DataGridRow object accessing the DataContext property of the sending RadioButton is sufficient:-
private void rdbIndataGrid_Checked(object sender, RoutedEventArgs e)
{
object myData = ((FrameworkElement)sender).DataContext;
if (myData != null)
lstOutput.Items.Add(String.Format("Checked: {0}", myData));
}
private void rdbIndataGrid_Unchecked(object sender, RoutedEventArgs e)
{
object myData = ((FrameworkElement)sender).DataContext;
if (myData != null)
lstOutput.Items.Add(String.Format("Unchecked: {0}", myData));
}
Hence you can dispense with the Ancestors extension method. However in more complex cases where the DataContext have been changed the original "over-complicated" approach may be needed.

Resources