Retrieve and save the Dynamic added control in WPF Xaml? - c#

I have added the template based on this link
I have an Add button - when I click on it through Command I add it to a collection.
<ItemsControl ItemsSource="{Binding Collection}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid DataContext="{StaticResource VieWModel}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="15*"/>
<ColumnDefinition Width="40*"/>
</Grid.ColumnDefinitions>
<Label Content="GH" Grid.Row="0" Grid.Column="0" VerticalContentAlignment="Center"></Label>
<tk:RadComboBox Grid.Row="0" Grid.Column="0" Margin="10" IsFilteringEnabled="True" Width="150" DisplayMemberPath="D" IsEditable="True" ItemsSource="{Binding GK}" SelectedItem="{Binding SK, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding SelectionChangedCommand}" CommandParameter="{Binding}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</tk:RadComboBox>
<Label Content="HB" Grid.Row="0" Grid.Column="1" VerticalContentAlignment="Center"></Label>
<tk:RadComboBox Grid.Row="0" Grid.Column="1" Margin="10" IsFilteringEnabled="True" Name="cb" Width="350" IsEditable="True" DisplayMemberPath="D" ItemsSource="{Binding VR}" SelectedItem="{Binding VR1,Mode=TwoWay}">
</tk:RadComboBox>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
ViewModel sample code:
// Property for selected Item in combox1
Public ValBase SK{get;set;}
//Property off combobox1 binding
Public ValBase GK{get;set;}
// Property ofor selected Item in combox2
Public ValBase VR1{get; set;}
//Property ofr combobox2 binding
Public ValBase VR{get;set;}
Public void AddButton(object obj)
{
var item =new collectionbase();
Collection.Add(item)
}
Whenever I click the Add Button this itemplate will be added.
MyRequirement :
When I Click Add Button for the first time ,template should get added
When I click Add Button for the second time Previous generated controls Must have contain the values,only then controls should be added to a collection and then new controls should be created
And I dont know how to save those values dynamically created in a collection
I am running out of Ideas how to achieve this can anyone help . MVVM pattern

I guess you are having Collection in MainViewModel and Command for add Model.
private Model _lastAdded;
public Model LastAdded
{
get{return _lastAdded;}
set{_lastAdded = value;}
}
private void AddCommand(object obj)
{
if(_lastAdded != null && _lastAdded.SelectedValue != null)
{
var newItem = new Model();
Collection.Add(newItem);
_lastAdded = newItem;
}
else
{
//Show message
}
}

Using Selector Class.I have used CurrentInstance To Bind the Collection its working fine now

Related

UWP - MVVM - Remove ListView item using ItemTemplate button

I have a screen displaying a list of items on which the user can click a button to remove the corresponding item from the list.
I am trying to do so using MVVM.
But the item is not aware of the containing list when it gets the action.
I saw some answers here and there, but none of them using out of the box MVVM features I have in my environment
For example that one using PRISM (don't know if I should use that too, is it standard?):
How to properly remove Items from a ListView when the ItemTemplate is a User Control?
Here is the XAML:
<ListView ItemsSource="{Binding MyItemList}" SelectionMode="None" ScrollViewer.VerticalScrollMode="Disabled" ItemContainerTransitions="{x:Null}">
<ListView.ItemTemplate>
<DataTemplate >
<Grid Grid.Row="1" HorizontalAlignment="Stretch" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="2*" />
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0" Text="{Binding ItemClass.Property01, Mode=TwoWay}" />
<Button Grid.Column="1" Command="{Binding RemoveItemCommand}" >
<SymbolIcon Symbol="Cancel" />
</Button>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
And here is the ModelView list:
private static ObservableCollection<ItemClass> _MyItemList = new ObservableCollection<ItemClass> {
new ItemClass{ Property01 = "Sometext" }
};
public ObservableCollection<ItemClass> MyItemList { get { return _MyItemList; } }
And I want to be able to perform the following (the example of code from the main model view, I could create an item model view if necessary for solving):
public IMvxCommand RemoveItemCommand { get; private set; }
public MyViewModel(IUserDialogs dialogs)
{
RemoveItemCommand = new MvxCommand(RemoveItem);
}
public void RemoveItem(object theItem) { MyItemList.Remove(theItem); }
Add x:Name="listView" attribute to your ListView, then in the template
<Button Grid.Column="1"
Command="{Binding ElementName=listView, Path=DataContext.RemoveItemCommand}"
CommandParameter="{Binding}" >
However, when I face problems like this, I usually just use code behind instead. The reason for that, I can use debugger for C# code in visual studio, but debugging these complex bindings is much harder. Here’s a C# version, the code is IMO cleaner, and easier to debug:
void removeItem_Click( object sender, RoutedEventArgs e )
{
object i = ((FrameworkElement)sender).DataContext;
( this.DataContext as MyViewModel )?.RemoveItem( i );
}
Or maybe that's just my personal preference.
It would be better to have a context menu item on the list view (or a delete button on the page somewhere) to delete the currently selected item(s). You can then get the selection from the list view.
Alternatively you could attach the context menu to the list view item in PrepareContainterForItemOverride (and detach it in the other Override method)
That would be a more standards interaction style.
If you must have the button inside the list view item, then the easiest way to get the list item would probably be to use a visual tree helper to go up from the button to the list view item and then get the actual item from the list view item.
Thanks for all the hints,
Using Soonts answer, I was able to develop a fast solution,
Here is what the final implementation looks like for reference for whoever wants to copy/paste/adapt (note I did not test code as I replaced variables/functions names):
XAML:
<ListView x:Name="ItemClass_ListView" ItemsSource="{Binding MyItemList}" SelectionMode="None" ScrollViewer.VerticalScrollMode="Disabled" ItemContainerTransitions="{x:Null}">
<ListView.ItemTemplate>
<DataTemplate >
<Grid Grid.Row="1" HorizontalAlignment="Stretch" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="2*" />
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0" Text="{Binding ItemClass.Property01, Mode=TwoWay}" />
<Button Grid.Column="1" Command="{Binding ElementName=ItemClass_ListView, Path=DataContext.RemoveItemCommand}" CommandParameter="{Binding}" >
<SymbolIcon Symbol="Cancel" />
</Button>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
ViewModel:
public class MyViewModel : BaseViewModel, INotifyPropertyChanged
{
public IMvxCommand RemoveItemCommand { get; private set; }
public MyViewModel()
{
// Initializing Commands
RemoveItemCommand = new MvxCommand<ItemClass>(OnRemoveItemClick);
}
public void OnRemoveItemClick(ItemClass anItem)
{
// Do stuff...
}
private static ObservableCollection<ItemClass> _MyItemList = new ObservableCollection<ItemClass> {
new ItemClass(),
new ItemClass()
};
public ObservableCollection<ItemClass> MyItemList
{
get { return _MyItemList; }
}
}

How to access SelectedItem of ComboBox inside DataTemplate

I have following XAML:
<ItemsControl x:Name="TextComboPairItemsControl" Grid.Row="1" Grid.ColumnSpan="2"
ItemsSource="{Binding Path=AllHeaders.Fields}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock x:Name="TextBlock1" Text="{Binding}"
Grid.Column="0" Margin ="2"/>
<ComboBox x:Name="ComboBox1" ItemsSource="{Binding ElementName=MainGrid, Path=DataContext.Tags}"
SelectedItem="{Binding ElementName=MainGrid, Path=DataContext.TextComboPairList.Combo}"
Grid.Column="1" Margin ="2" SelectedIndex="0" IsEditable="True"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Now, in my code I want to be able to read what the user has chosen in each ComboBox. For that I created a class:
public class TextComboPair
{
public string TextContent { get; set; }
public string ComboContent { get; set; }
}
Every pair of TextBlock and ComboBox would have its own object of the above class.
I also created a list to store all those pairs of data:
public List<TextComboPair> TextComboPairList
{
get;
set;
}
It is defined in my DataContext.
So, if, for example, there was displayed a list of three TextBlock-ComboBox pairs on the screen and user would choose what he needs in each ComboBox, I'd like to have the above List populated with that data.
As you can see in XAML I bound Selected Item to this List, but I must have done it wrong.
Hwo can I fix this?
Try this :
<ComboBox x:Name="ComboBox1" ItemsSource="{Binding Path=DataContext.Tags, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl }}}"
SelectedItem="{Binding RelativeSource={RelativeSource AncestorType={x:Type ItemsControl }}, Path=DataContext.TextComboPairList.Combo}"
Grid.Column="1" Margin ="2" SelectedIndex="0" IsEditable="True"/>

Send a FlipViewItem as a RelayCommandParameter in a Windows Store App

I am trying to send to a view model the current item of a FlipView control, using MVVM Light.
The XAML code representing the FlipView control is the following:
<FlipView x:Name="mainFlipView" Margin="0,10,0,10" ItemsSource="{Binding AlbumItems, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<FlipView.ItemTemplate>
<DataTemplate>
<Grid Margin="5">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Text="{Binding Caption}"
FontSize="23"
HorizontalAlignment="Center"
TextAlignment="Center"
TextWrapping="Wrap"
Margin="10"/>
<ScrollViewer Grid.Row="1" ZoomMode="Enabled">
<uc:ImageViewer FilePath="{Binding ImagePath}" />
</ScrollViewer>
<TextBlock Text="{Binding NrOfVotes}" FontSize="20"
Grid.Row="2" HorizontalAlignment="Center"
Margin="10" />
</Grid>
</DataTemplate>
</FlipView.ItemTemplate>
</FlipView>
...
The XAML code of the item containing the relay command is:
<Page.BottomAppBar>
<CommandBar>
<AppBarButton x:Name="appBarButtonDelete" Label="Delete" Icon="Delete"
Command="{Binding DeleteItemCommand}"
CommandParameter="{Binding ElementName=mainFlipView, Path=SelectedItem}"/>
</CommandBar>
</Page.BottomAppBar>
In the ViewModel, the RelayCommand is declared and used as follows:
public class ResultsPageViewModel : ViewModelBase
{
public RelayCommand<MyModel> DeleteItemCommand { get; private set; }
public ResultsPageViewModel()
{
this.DeleteItemCommand = new RelayCommand<MyModel>(post => DeleteItem(post));
}
public void DeleteItem(MyModel p)
{
//P is always null here...
}
}
The problem is that in the DeleteItem function I always get the parameter as null. I have tried declaring the RelayCommand as RelayCommand<object> but the problem persists.
I also tried the "workaround" method of declaring a MyModel bindable property and binding it to the FlipView. It works, but I would like to know what am I doing wrong in this situation.
Thank you in advance!
Try a different strategy: take the parameter directly from ViewModel, after a proper binding.
XAML
<FlipView x:Name="mainFlipView"
Margin="0,10,0,10"
ItemsSource="{Binding AlbumItems, Mode=TwoWay }"
SelectedItem="{Binding AlbumSelectedItem, Mode=TwoWay}">
ViewModel
private MyModel albumSelectedItem;
public MyModel AlbumSelectedItem
{
get
{
return albumSelectedItem;
}
set
{
if (value != null && albumSelectedItem != value)
{
albumSelectedItem = value;
RaisePropertyChanged(() => AlbumSelectedItem);
}
}
}
public void DeleteItem(MyModel p)
{
//P is always null here...
var pp = AlbumSelectedItem;
}
Obviously, CommandParameter is useless. ;-)

How to show data from selected item in listbox wpf using mvvm?

I am just doing some practice on WPF & MVVM forms
So far, I have just completed the normal Listbox with data loaded from an array, that when the index changes, it loads other data into textblocks on the form
I would like to change this example however. I want the user to select a field in the listbox, then click a button to display all the other data
So, the form is (usercontrol):
And when someone selects, say Cena, they will see the data on the right filled out.
My code for the .xaml is:
<UserControl x:Class="SuperstarsRoster.RosterView"
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:SuperstarsRoster"
xmlns:WpfToolkit="http://schemas.microsoft.com/wpf/2008/toolkit"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="600">
<UserControl.DataContext>
<local:RosterViewModel/>
</UserControl.DataContext>
<Grid x:Name="LayoutRoot" Background="White" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="250"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<!--SelectedItem="{Binding SelectedPerson}"-->
<ListBox Grid.Column="0" Margin="0"
ItemsSource="{Binding RosterList}"
DisplayMemberPath="Name"
Name="lstRoster"
Height="250"
VerticalAlignment="Top"/>
<Button Content="Exit" Height="23" HorizontalAlignment="Left" VerticalAlignment="Bottom" Name="btnExit" Width="150" Command="{Binding ButtonCommand}" CommandParameter="Hai" />
<Grid x:Name="PersonDetails" Grid.Column="1" DataContext="{Binding SelectedPerson}" Margin="5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="150"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition Height="20"/>
<RowDefinition Height="20"/>
<RowDefinition Height="20"/>
<RowDefinition Height="20"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Grid.ColumnSpan="2" Text="Person Details" FontSize="15"/>
<TextBlock Grid.Row="1" Grid.Column="0" Text="Name"/>
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Name,Mode=TwoWay}"/>
<TextBlock Grid.Row="2" Grid.Column="0" Text="Brand"/>
<TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding Brand,Mode=TwoWay}"/>
<TextBlock Grid.Row="3" Grid.Column="0" Text="Type"/>
<TextBlock Grid.Row="3" Grid.Column="1" Text="{Binding Type,Mode=TwoWay}"/>
<Button Grid.Row="4" Content="Choose" Height="23" HorizontalAlignment="Left" VerticalAlignment="Bottom" Name="btnChoose" Width="90" Command="{Binding ChooseCommand}" CommandParameter="{Binding ElementName=lstRoster,Path=SelectedPerson}" />
</Grid>
</Grid>
my problem is the Show button:
<Button Grid.Row="4" Content="Choose" Height="23" HorizontalAlignment="Left" VerticalAlignment="Bottom" Name="btnChoose" Width="90" Command="{Binding ChooseCommand}" CommandParameter="{Binding ElementName=lstRoster,Path=SelectedPerson}" />
I don't know what to do here. I don't know if the CommandParameters should be empty, or have something in it.
My ViewModel code is:
#region Show Button
private ICommand m_ShowCommand;
public ICommand ShowCommand
{
get
{
return m_ShowCommand;
}
set
{
m_ShowCommand = value;
}
}
public void Selected(object obj)
{
RaisePropertyChanged("SelectedPerson");
}
#endregion
I have a feeling my Selected is the incorrect piece of code. On the ViewModel code there is also:
#region Roster Details
public ObservableCollection<Roster> rosterList;
public Roster selectedPerson;
public RosterViewModel()
{
ButtonCommand = new RelayCommand(new Action<object>(ShowMessage));
ShowCommand = new RelayCommand(new Action<object>(Selected));
rosterList = new ObservableCollection<Roster>()
{
new Roster(){Name="Batista", Brand="Smackdown!", Type="Heel"},
new Roster(){Name="The Rock", Brand="RAW", Type="Face"},
new Roster(){Name="John Cena", Brand="RAW", Type="Face"},
new Roster(){Name="Randy Orton", Brand="Smackdown!", Type="Heel"}
};
RaisePropertyChanged("SelectedPerson");
}
#endregion
With the ShowCommand being the button event, but I don't know what to put here.
Ideally, user selects Cena, clicks show, and the textblocks will fill with the data from the array.
My RelayCommand class (the default for all button clicks) looks like so:
class RelayCommand : ICommand
{
private Action<object> _action;
public RelayCommand(Action<object> action)
{
_action = action;
}
#region ICommand Members
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
_action(parameter);
}
#endregion
Should there be something more here? Or in the ViewModel?
I'm using MVVM, so there is no code in my code behind class.
The Exit button works, that's why I know the commands will work.
EDIT
I changed some of the code now. Firstly, the show button was sitting in a grid that had a datacontext setting. That was taken out. Next, both buttons share the same command (ButtonCommand), but both have different parameters. Exit is "Exit", and choose is "Hai"
In the ViewModel code, the following was added and changed
public string Name { get; set; }
public string Brand { get; set; }
public string Type { get; set; }
#region Button Work
private ICommand m_ButtonCommand;
public ICommand ButtonCommand
{
get
{
return m_ButtonCommand;
}
set
{
m_ButtonCommand = value;
}
}
public void DoAction(object obj)
{
if (obj.ToString() == "Hai")
{
if (selectedPerson != null)
{
this.Name = selectedPerson.Name;
this.Brand = selectedPerson.Brand;
this.Type = selectedPerson.Type;
RaisePropertyChanged(null);
}
}
if (obj.ToString() == "Exit")
{
MessageBox.Show("This program will now close");
Environment.Exit(0);
}
}
#endregion
This way, data is set and I can populate the fields when wanted.
Along with initializing it first
public RosterViewModel()
{
ButtonCommand = new RelayCommand(new Action<object>(DoAction));
So, it works now.
You have a couple of choices really:
(1) Have a VM property that is bound to the SelectedItem of your ListBox, and then you don't need to send any parameters with your button command ... you can just perform your ChooseCommand on the currently SelectedItem (as known by you VM).
or
(2) Pass in the SelectedItem as a parameter on your command, like this ...
<Button Grid.Row="4" Content="Choose" Height="23" HorizontalAlignment="Left"
VerticalAlignment="Bottom" Name="btnChoose" Width="90"
Command="{Binding ChooseCommand}"
CommandParameter="{Binding ElementName=MyListBox,Path=SelectedItem}" />
Note that you will need to give your ListBox a name (x:Name="MyListBox") and that your CommandParameter is referring to that ListBox, and its SelectedItem property.

DataBinding To Two Sources

I have a need to use two listboxes, each bound to a different collection.
i originally had this working with one listbox and binding before the need to bind two came up.
Here is how I was doing that.
<Window x:Class="TeamManager.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc ="clr-namespace:TeamManager"
Title="Game Manager" Height="800" Width="800">
<Window.Resources>
<DataTemplate DataType="{x:Type loc:Game}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"></ColumnDefinition>
<ColumnDefinition Width="100"></ColumnDefinition>
<ColumnDefinition Width="100"></ColumnDefinition>
<ColumnDefinition Width="100"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Name="dateBlock" Grid.Column="0" Grid.Row="1" Text="{Binding Date, StringFormat=d}"></TextBlock>
<TextBlock Name="TimeBlock" Grid.Column="1" Grid.Row="1" Text="{Binding Time}"></TextBlock>
<Button Grid.Row="1" Grid.Column="2" CommandParameter="{Binding Id}" Click="Manage_Click" >Manage</Button>
<Button Grid.Row="1" Grid.Column="3" CommandParameter="{Binding Id}" Click="Delete_Click" Height="16" Width="16">
<Image Source="/Images/DeleteRed.png"></Image>
</Button>
</Grid>
</DataTemplate>
</Window.Resources>
<StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
<StackPanel>
<TextBlock>Upcomming Games</TextBlock>
<ListBox ItemsSource="{Binding}" Name="GameList"></ListBox>
</StackPanel>
<StackPanel Orientation="Vertical" HorizontalAlignment="Left">
<Button Height="30" Width="100" Margin="10,10,10,10" Click="AddGame_Click">Add New Game</Button>
</StackPanel>
</StackPanel>
</StackPanel>
And my code simply set the DataContext of the window to a ObservableCollection
with the need to use TWO collections I created a wrapper class like this
public class AppModel
{
public ObservableCollection<Game> gameCollection { get; set; }
public ObservableCollection<Player> playerCollection { get; set; }
}
And my CS is now setting the DataContext to an object of AppModel
GameDBEntities _entity = new GameDBEntities();
AppModel _model;
public MainWindow()
{
InitializeComponent();
DataContext = model;
}
AppModel model
{
get
{
if (_model == null)
{
_model = new AppModel();
}
if (_model.gameCollection == null)
{
_model.gameCollection = new ObservableCollection<Game>(_entity.Games);
}
if (_model.playerCollection == null)
{
_model.playerCollection = new ObservableCollection<Player>(_entity.Players);
}
return _model;
}
set { }
}
In my Xaml, how can I set the datacontext of the existing listBox to be bound to the Collection Of Games in The AppModel?
Once I get that working I will work on the second listbox on my own.
Thanks!
You need to add a Path to the Binding. The DatacContext will be the model, the path should point to either collection:
<ListBox ItemsSource="{Binding gameCollection}" ...
Would changing the Binding to <ListBox ItemsSource="{Binding Path=gameCollection}" Name="GameList"></ListBox> solve your problem?
As per your question you state that you used to set the DataContext to the gameCollection, but now that you have changed this to use the AppModel, you will need to also change your binding as appropriate.
This will essentially change the Binding from being just bound to gameCollection, it will now be set to use AppData.gameCollection.

Categories

Resources