Im building a WPF application and trying to stick to the MVVM pattern as much as possible. I have a list box with a data template inside of it that contains a TextBlock and Button. If the button within the data template is clicked it does not select the entire row, so I am unaware of what row it pertains to. I would like to grab the entire object and bind it to a property in the view model. Can I get some help or a workaround for this please that sticks to mvvm pattern.
List box with item template
<telerik:RadListBox Width="200" Height="150" HorizontalAlignment="Left" Margin="10" ItemsSource="{Binding ListOfSupplierInvoices}"
SelectedItem="{Binding SelectedSupplierInvoice, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<telerik:RadListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch" >
<TextBlock Text="{Binding InvoiceNumber}" HorizontalAlignment="Left" Margin="5" ></TextBlock>
<telerik:RadButton Height="20" >
<telerik:RadButton.Content>
<Image Source="/ImageResources/Misc/delete.png" Stretch="Fill" />
</telerik:RadButton.Content>
</telerik:RadButton>
</StackPanel>
</DataTemplate>
</telerik:RadListBox.ItemTemplate>
</telerik:RadListBox>
How it looks in the view:
As far as I understand your code, the button corresponds to a delete command, which means you want to delete the item associated with the button. In this case, the selection might not need to change, you just have to pass the current item to the delete command.
Add a Delete command to your view model like this:
public class MyViewModel : ViewModelBase
{
public MyViewModel()
{
Delete = new DelegateCommand(ExecuteDelete, CanExecuteDelete);
// ...other code.
}
public ICommand Delete { get; }
private void ExecuteDelete(object obj)
{
var invoiceItem = (InvoiceItem) obj;
// Use this only if you need the item to be selected.
// SelectedSupplierInvoice = invoiceItem;
// ...your delete logic.
}
private bool CanExecuteDelete(object obj)
{
// ...your can execute delete logic.
}
// ...other code.
}
Note that I introduced InvoiceItem as item type, because I do not know your item type, simply adapt it. The Delete command gets the current item passed as parameter. If you can always remove the item, there is no need in selecting it, as it is gone afterwards.
Otherwise, uncomment the line so the SelectedSupplierInvoice is set to the item which will automatically update the user interface through the two-way binding if you have implemented INotifyPropertyChanged correctly or derive from ViewModelBase which exposes the RaisePropertyChanged or OnPropertyChanged method, e.g.:
private InvoiceItem _selectedSupplierInvoice;
public InvoiceItem SelectedSupplierInvoice
{
get => _selectedSupplierInvoice;
set
{
if (_selectedSupplierInvoice == value)
return;
_selectedSupplierInvoice = value;
RaisePropertyChanged();
}
}
In your XAML wire the button to the Delete command on the DataContext of the RadListBox.
<telerik:RadButton Height="20"
Command="{Binding DataContext.Delete, RelativeSource={RelativeSource AncestorType={x:Type telerik:RadListBox}}}"
CommandParameter="{Binding}">
<telerik:RadButton.Content>
<Image Source="/ImageResources/Misc/delete.png" Stretch="Fill" />
</telerik:RadButton.Content>
</telerik:RadButton>
Related
I have a problem for which I'm searching an explanation. It's similar to what's been discussed in WPF ComboBox SelectedItem Set to Null on TabControl Switch, but it's involving a lesser degree of binding and so should be open to simpler solutions. What I'm describing below is a simplified case I've built to reproduce and try to understand why the problem is arising.
So, the project is based on MVVM, and the main window has just a button labelled "Search", declared as follows:
<Button Margin="50,0,0,0" Width="150" Height="40" Content="Search" HorizontalAlignment="Left" Command="{Binding UpdateViewCommand}" CommandParameter="Search"/>
The code is bound to UpdateView :ICommand that, is defined as follows:
class UpdateViewCommand : ICommand
{
private MainViewModel viewModel;
public UpdateViewCommand(MainViewModel viewModel)
{
this.viewModel = viewModel;
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
if (parameter.ToString() == "Search")
{
viewModel.SelectedViewModel = new SearchViewModel();
}
}
}
This view overlaps with the main one in the upper part, leaving the "Search" button visible, as shown in the picture below:
The view includes a ComboBox and a "Go" button, declared as:
<ComboBox Name="SearchCriterion" Canvas.Left="128" Canvas.Top="14" Height="22" Width="257" Background="#FF66CCFF" BorderBrush="Black" SelectedIndex="0"
SelectedItem="{Binding QueryType, Mode=OneWayToSource}">
<ComboBoxItem FontFamily="Calibri" FontSize="14" Background="#FF66CCFF">
Author
</ComboBoxItem>
<ComboBoxItem FontFamily="Calibri" FontSize="14" Background="#FF66CCFF">
Title
</ComboBoxItem>
</ComboBox>
<Button Name="SearchButton" Height="22" Content="Go" Canvas.Left="390" Canvas.Top="44" Width="45" BorderBrush="Black"
FontFamily="Calibri" FontSize="14" Background="#FF0066FF" Command="{Binding ExecQueryCmd}" Foreground="White"/>
All the button does is getting the ComboBoxItem value bound in the ComboBox declaration through the variable QueryType and print it. QueryType is declared as:
private ComboBoxItem _queryType = new ComboBoxItem();
public ComboBoxItem QueryType
{
get { return _queryType; }
set
{
Globals.mylog.Trace("In SearchViewModel.QueryType");
_queryType = value;
OnPropertyChanged(nameof(QueryType));
}
}
Assuming this is clear, here is the problem I see. I start the program, click on "Search" and the SearchView appears. I play with the ComboBox, click "Go" and all is fine. I can do this several times, no problem.
Now I click on "Search" again. No apparent change (the view is already there), but if I click on "Go" an exception is raised because the variable is null (I'm running under Visual Studio, so I can easily check). Note that if, instead of clicking "Go" right after clicking on "Search", I click on the ComboxBox and change its value before, everything works fine.
Can anyone explain me why this is happening, and how I can solve it?
Thanks
You never explicitly assigned a value to QueryType in the constructor of SearchViewModel, so the value in querytype was depending on the UI to update it.
A better way is to have the selectedvalue come from the viewmodel (and not have ui elements in tour viewmodels as I mentionned in the comments).
What I changed to make it works:
In SearchViewModel:
/// <summary>
/// Selected option to search by (it is now a string)
/// </summary>
private string _queryType;
public string QueryType
{
get { return _queryType; }
set
{
Globals.mylog.Trace("In SearchViewModel.QueryType");
_queryType = value;
OnPropertyChanged(nameof(QueryType));
}
}
/// <summary>
/// List of options to search by
/// </summary>
public ObservableCollection<string> Queries { get; set; }
public SearchViewModel()
{
Globals.mylog.Trace("In SearchViewModel");
//Initialization ofthe list of options
Queries = new ObservableCollection<string> { "Author", "Title" };
//Initialization of the selected item
this.QueryType = Queries.FirstOrDefault();
ExecQueryCmd = new RelayCommand(ExecuteQuery, CanExecuteQuery);
}
In SearchView:
<--The combobox is now bound to the list in the ViewModel(the data is stored in the viewmodels and the view is only responsible for displaying it) -->
<Canvas Width="517" Height="580" Background="#FFCCFF99">
<ComboBox Name="SearchCriterion" Canvas.Left="128" Canvas.Top="14" Height="22" Width="257" ItemsSource="{Binding Queries}" Background="#FF66CCFF" BorderBrush="Black"
SelectedItem="{Binding QueryType, Mode=TwoWay}">
<ComboBox.ItemContainerStyle>
<Style BasedOn="{StaticResource {x:Type ComboBoxItem}}" TargetType="{x:Type ComboBoxItem}">
<Setter Property="FontFamily" Value="Calibri"/>
<Setter Property="FontSize" Value="14"/>
<Setter Property="Background" Value="#FF66CCFF"/>
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
<Button Name="SearchButton" Height="22" Content="Go" Canvas.Left="390" Canvas.Top="44" Width="45" BorderBrush="Black"
FontFamily="Calibri" FontSize="14" Background="#FF0066FF" Command="{Binding ExecQueryCmd}" Foreground="White"/>
</Canvas>
Please help!
I did many research on the internet, but didn't find any solution for my question.
I have a form with foods. There is a grid on the form and with it I can navigate on the food table. There is a combobox on the screen (not in the grid) which contains the categories. The combobox is filled up with the categories from categories table. When I change the record on the datagrid every field updated on the form except the combobox.
first record
second record
So my question is: what I have to do to refresh the combobox, to show the saved category when I navigate on the grid?
In the category table the category has "id" field and in the food table there is a "categoryid" field.
I have this in the xaml file:
<ComboBox x:Name="categoryComboBox" Grid.Row="5" Grid.Column="1" Margin="3,4,20,0" Grid.ColumnSpan="3"
ItemsSource="{Binding Source={StaticResource categoryViewSource}}"
SelectedValuePath="CategoryId"
DisplayMemberPath="CatName"
SelectedItem="{Binding CategoryId, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Height="25" VerticalAlignment="Top">
<ComboBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel/>
</ItemsPanelTemplate>
</ComboBox.ItemsPanel>
</ComboBox>
As I can see you have a small error in your code. I should use the SelectedValue instead of SelectedItem. So change it and I think it will work properly. And in addition You don't need any workaround with the scaling as I suggested before.
Here is example:
XAML
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" >
<ComboBox x:Name="categoryComboBox" ItemsSource="{Binding Source={StaticResource categoryViewSource}}"
SelectedValuePath="CategoryId"
DisplayMemberPath="CatName"
SelectedValue="{Binding CategoryId, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Height="25" VerticalAlignment="Top">
<ComboBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel/>
</ItemsPanelTemplate>
</ComboBox.ItemsPanel>
</ComboBox>
<Button Content="Change Category" Command="{Binding SelectionChangedCommand}"></Button>
</StackPanel>
DataContext
public class MyComboDataContext:BaseObservableObject
{
private int _categoryId;
private ICommand _selectionChangedCommand;
public MyComboDataContext()
{
CategoryId = 1;
}
public int CategoryId
{
get { return _categoryId; }
set
{
_categoryId = value;
OnPropertyChanged();
}
}
public ICommand SelectionChangedCommand
{
get { return _selectionChangedCommand ?? (_selectionChangedCommand = new RelayCommand(SelectionChanger)); }
}
private void SelectionChanger()
{
CategoryId += 1;
if (CategoryId == 4)
CategoryId = 1;
}
}
Explanations:
First of all, this is an example that is simulating the update of a combo. Here the combobox selected value is changed on each button click. In your example the category selection should effect the combo selected value. So each time the grid category selection happens you should push selected category id into the property the combo SelectedValue is bound to it.
In order to help you please update your question with next things:
Are there any Binding expression errors in your output window?
How do you handle a DataGrid selection in your code.
How the data grid selection effects the combobox SelectedValue(it have to be selected value)?
Let me know if you need more help. And feel free to mark you question as answered if my answer was helpful.
In my WPF application, I have a ListBox in my main screen. I'm trying to use the MVVM pattern, so I have a ViewModel associated with the View. When I launch the application, my ViewModel gets initiated, and it reads in a bunch of DLLs I've placed in a directory. Each DLL contains a "Strategy" class, so when I read the DLLs, I retrieve these Strategy class objects and put them in a list (actually an ObservableCollection) which is a member of my ViewModel. I'm using this member list, named DllList, to populate the ListBox.
My ViewModel looks like the following (unnecessary bits removed for clarity):
public class ViewModelPDMain : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName) {
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public ViewModelPDMain() {
dllList = new ObservableCollection<Strategy>();
selectedStrategy = new Strategy();
}
private ObservableCollection<Strategy> dllList = null;
private Strategy selectedStrategy = null;
public ObservableCollection<Strategy> DllList
{
get { return dllList; }
set {
dllList = value;
RaisePropertyChanged("DllList");
}
}
public Strategy SelectedStrategy
{
get { return selectedStrategy; }
set {
selectedStrategy = value;
RaisePropertyChanged("SelectedStrategy");
}
}
}
Then in my main View, I bind it as follows.
<Window x:Class="PrisonersDilemma.Source.View.ViewPDMain"
xmlns:local="clr-namespace:PrisonersDilemma.Source.View"
DataContext="{Binding Source={StaticResource mainViewModelLocator}, Path=ViewModelPDMain}"
Title="Iterated Prisoner's Dilemma" Height="500" Width="800" MinHeight="500" MinWidth="800">
<Grid Name="gridMain">
...
<!-- More stuff here -->
...
<ListBox Name="listStrategies" SelectedIndex="0"
ItemsSource="{Binding DllList}" SelectedItem="{Binding SelectedStrategy}"
Grid.Column="0" Grid.Row="1" Grid.RowSpan="2"
Width="Auto" MinWidth="120"
Margin="3"
BorderBrush="LightGray" BorderThickness="1">
</ListBox>
...
<!-- More stuff here -->
...
</Grid>
</Window>
When I do this and run the application my list box looks like below which is expected.
The problem is when I try to display a property inside my Strategy objects. My Strategy class contains another class, named StratInfo, which in turn contains a string property, StrategyName. My requirement is to display this string value as listbox item values instead of what you can see above.
So I do the following in my View:
<Window x:Class="PrisonersDilemma.Source.View.ViewPDMain"
xmlns:local="clr-namespace:PrisonersDilemma.Source.View"
DataContext="{Binding Source={StaticResource mainViewModelLocator}, Path=ViewModelPDMain}"
Title="Iterated Prisoner's Dilemma" Height="500" Width="800" MinHeight="500" MinWidth="800">
<Grid Name="gridMain">
...
<!-- More Stuff Here -->
...
<ListBox Name="listStrategies" SelectedIndex="0"
ItemsSource="{Binding DllList}" SelectedItem="{Binding SelectedStrategy}"
Grid.Column="0" Grid.Row="1" Grid.RowSpan="2"
Width="Auto" MinWidth="120"
Margin="3"
BorderBrush="LightGray" BorderThickness="1">
<!-- Added Stuff -->
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Label Name="lblFirstName"
Content="{Binding SelectedStrategy.StratInfo.StrategyName, Mode=OneWay}"
Grid.Column="0"></Label>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
...
<!-- More Stuff Here -->
...
</Grid>
</Window>
When I do this, I expect the list box items to contain a label, and it to display my StrategyName value. However, I get a listbox which contains 25 items (I have 25 DLLs), but all 25 items are empty.
Funny thing is, I tried to bind the SelectedStrategy.StratInfo.StrategyName to a text box Text property, and it worked. That is, when I click any empty listbox item, it displays the StrategyName in the text box. Please refer to the following figure. You can see that the listbox contains items but the content values aren't displayed. In addition, to the right, the Strategy Name text box is a text box where I have bound the SelectedStrategy.StratInfo.StrategyName and it displays the correct value on item select event.
I have done this exact same thing in a simpler project, and it works just fine. I can't figure out what I'm doing wrong here.
Any thoughts?
Your binding in the data template is incorrect. The data context within the data template is an item in the DllList which is of type Strategy. So your Label should be like so:
<Label Name="lblFirstName"
Content="{Binding StratInfo.StrategyName, Mode=OneWay}"
Grid.Column="0"/>
I know this was already asked a lot, but I didn't find any solution.
My ListView looks like this
<ListView Margin="0,0,0,0" x:Name="ContactListView" BorderBrush="Black" ItemsSource="{Binding RosterItemX}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="25">
<Image Tag="{Binding Availability}" Margin="0,0,5,0" Width="16" Height="16" VerticalAlignment="Center">
</Image>
<TextBlock Text="{Binding Name}" VerticalAlignment="Center"/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
<Custom:EventToCommand Command="{Binding ContactDblClicked, Mode=OneWay}" PassEventArgsToCommand="True" />
</i:EventTrigger>
</i:Interaction.Triggers>
</ListView>
I have my ICommand in my viewmodel:
public ICommand ContactDblClicked { get { return new RelayCommand<MouseButtonEventArgs>(contactDblClicked); } }
This event fires everytime someone double clicks into the ListView. Doesn't have to be on a ListViewItem.
I can handle the case when no ListViewItem is selected.
I cast (ListView)e.Source, and check if an Item is selected.
I need a way to check if what is double clicked is actually a ListViewItem and not empty space.
Not entirely sure what you mean by your last line I need a way to check if what is double clicked is actually a ListViewItem and not empty space., but here are two suggestions:
First, if you want to check if an item is selected in your ListView:
private void contactDblClicked(MouseButtonEventArgs obj)
{
var listView = obj.Source as ListView;
if (listView != null)
{
if (listView.SelectedItem != null)
{
Debug.WriteLine("item selected");
}
else
{
Debug.WriteLine("item not selected");
}
}
}
However, I think you already got that solution and if I understand your question right, you want to check if the user actually clicked an item (and not whitespace) even if an item is selected.
So here is the second approach to check if an item was really clicked:
private void contactDblClicked(MouseButtonEventArgs obj)
{
if (((FrameworkElement) obj.OriginalSource).DataContext is YourRosterItemXType)
{
Debug.WriteLine("item was *really* clicked");
}
}
Where YourRosterItemXType is the type of your binded RosterItemX property. With the above code you check, if the DataContext of the original source of the mouse event is set to YourRosterItemXType. Items in your ListView have that DataContext set and so you check if that mouse event comes really from one of those list items.
I have two WPF windows developed using the surface SDK, one that is a data entry form, and the second dispays the data in a listbox. The listbox displays the data perfectly but when I add a new record using the data entry form, the listbox is not updated until I reopen the window. Is there a way to automatically update the listbox through binding or something?
This is the listbox code:
<s:SurfaceListBox Height="673" Margin="0,26,0,31" Name="surfaceListBox1" ItemsSource="{Binding Path={}}" Width="490">
<s:SurfaceListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Label Width="80" FontSize="8" Content="{Binding Path=item1}"></Label>
<Label Width="80" FontSize="8" Content="{Binding Path=item2}"></Label>
<Label Width="210" FontSize="8" Content="{Binding Path=item3}"></Label>
<Label Width="80" FontSize="8" Content="{Binding Path=item4}"></Label>
<Label Width="60" FontSize="8" Content="{Binding Path=item5, Converter={StaticResource booleanconverter}}"></Label>
</StackPanel>
</DataTemplate>
</s:SurfaceListBox.ItemTemplate>
</s:SurfaceListBox>
I am using Visual C# 2008 and the code to fill the listbox is:
private SHIPS_LOGDataSet ShipData = new SHIPS_LOGDataSet();
private SHIPS_LOGDataSetTableAdapters.MAINTableAdapter taMain = new SHIPS_LOGDataSetTableAdapters.MAINTableAdapter();
private SHIPS_LOGDataSetTableAdapters.TableAdapterManager taManager = new ShipsLogSurface.SHIPS_LOGDataSetTableAdapters.TableAdapterManager();
private void SurfaceWindow_Loaded(object sender, RoutedEventArgs e)
{
this.taMain.Fill(this.ShipData.MAIN);
this.DataContext = from MAIN in this.ShipData.MAIN orderby MAIN.MESSAGE_ID descending select MAIN;
}
The only table in my database is called MAIN.
I'm guessing I might have to use a collection view or similar but don't know how to implement that. Any ideas would be much appreciated. Thanks
INotifyPropertyChanged is an interface which you should implement in your data class (ShipData?). The properties in your data class should look as follows:
private string _myField;
public string MyField {
get { return _myField; }
set { _myField = value; onPropertyChanged(this, "MyField"); }
}
So whenever something in your data class changes (i.e. add/delete/update), it will fire the OnPropertyChanged event.
Your List or ObservableCollection that you use to populate the list listens to this OnPropertyChanged event and will update itself whenever the event is fired.
Try to do it with INotifyPropertyChanged.
surfaceListBox1.Items.Refresh();