I am working on a WPF app where I need to dynamically create GroupBoxes(which contains combobxes, sliders and togglebutton) based on Button Click. I have two xaml files in my View Folder. 'CodecView.xaml' and 'CodecWidgetView.xaml'.
CodecView.XAML:
<Grid>
<ScrollViewer Name="GroupBoxScroll" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0" >
<Grid Name="NumberofCodecs" Style="{DynamicResource styleBackground}" />
</ScrollViewer>
</Grid>
<Button Content="Add Box" Name="AddBoxBtn" Command="{Binding AddGroupBoxCommand}" />
CodecWidgetView.xaml:
<GroupBox Header="{Binding GroupBoxHeader}" Height="Auto" HorizontalAlignment="Stretch" Margin="5,5,0,0" Name="groupBox1" VerticalAlignment="Stretch" Width="Auto">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<ToggleButton Name="FrequencyBox" Content="Master" Grid.Column="1" Height="25" Width="50" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="0" />
<ComboBox Grid.Column="2" Height="23" HorizontalAlignment="Center" Margin="0,0,0,0" Name="comboBox2" VerticalAlignment="Center" Width="80" />
<ComboBox Grid.Column="0" Height="23" HorizontalAlignment="Center" Margin="0,0,0,0" Name="comboBox1" VerticalAlignment="Center" Width="80" />
</Grid>
s
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<ToggleButton Name="OneSixBit" Content="16 Bit" Grid.Column="0" Height="25" Width="45" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="0" />
<ToggleButton Name="ThreeTwoBit" Content="32 Bit" Grid.Column="3" Height="25" Width="45" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="0" />
<ToggleButton Name="TwentyBit" Content="20 Bit" Grid.Column="1" Height="25" Width="45" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="0" />
<ToggleButton Name="TwentyFourBit" Content="24 Bit" Grid.Column="2" Height="25" Width="45" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="0" />
</Grid>
<Grid Grid.Row="2">
<Label Name="BitDelay" Content="Bit Delay" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="0,0,205,0" Height="25" Width="55" />
<Slider Height="23" HorizontalAlignment="Center" Minimum="0.0" Maximum="255.0" TickFrequency="1.0" Margin="95,0,0,0" Name="bitdelayslider" VerticalAlignment="Center" Width="160" />
<TextBox Name="BitDelayValue" IsReadOnly="True" Text="{Binding ElementName=bitdelayslider,Path=Value}" Width="40" Height="20" Margin="0,0,110,0" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid>
<Grid Grid.Row="3">
<Label Name="DBGain" Content="DB Gain" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="0,0,205,0" Height="25" Width="55" />
<TextBox Name="DBGainValue" IsReadOnly="True" Text="{Binding ElementName=dbgainslider,Path=Value}" Width="40" Height="20" Margin="0,0,110,0" HorizontalAlignment="Center" VerticalAlignment="Center" />
<Slider Height="23" HorizontalAlignment="Center" Minimum="0.0" Maximum="59.5" TickFrequency="0.5" Margin="95,0,0,0" Name="dbgainslider" VerticalAlignment="Center" Width="160" />
</Grid>
</Grid>
</GroupBox>
CodecViewModel: Is a view model of CodecView.xaml
/// <summary>
/// Event for Refresh Button
/// </summary>
private ICommand mAddGroupBoxCommand;
public ICommand AddGroupBoxCommand
{
get
{
if (mAddGroupBoxCommand == null)
mAddGroupBoxCommand = new DelegateCommand(new Action(mAddGroupBoxCommandExecuted), new Func<bool>(mAddGroupBoxCommandCanExecute));
return mAddGroupBoxCommand;
}
set
{
mAddGroupBoxCommand = value;
}
}
public bool mAddGroupBoxCommandCanExecute()
{
return true;
}
public void mAddGroupBoxCommandExecuted()
{
//Here It should display the groupbox 4 times
}
ModelClass:
private string GroupBoxHeaderName;
public string GroupBoxHeader
{
get
{
return GroupBoxHeaderName;
}
set
{
GroupBoxHeaderName = value;
OnPropertyChanged("GroupBoxHeader");
}
}
Thus I want to add this Groupbox present in CodecWidgetView.xaml to my grid(NumberofCodecs) in CodecView.xaml on startup. And when I click the AddBoxButton it should dynamically generate the groupbox 4 times and display it :)
Now this is tricky, each Groupbox Header must display different names in every dynamically generated groupbox. Lets say on startup, 2 groupboxes are already displayed with Groupbox Header = "Location 1" and GroupBox Header = "Location 2". On AddgroupBox button click I want to have 4 groupboxes with Header as Groupbox Header = "Location 3" Groupbox Header = "Location 4" Groupbox Header = "Location 5" Groupbox Header = "Location 6".
Is it possible? :)
In the following code i am taking a itemscontrol in "CodecView.xaml" and for that itemscontrol ItemTemplate is your "CodecWidgetView.Xaml" and added description to that datatemplate. i have created another class CodecWidgetViewModel.cs which will be view model for "CodecWidgetView" view.
In the constructor of "CodecViewModel" i am creating instance for "CodecWidgetViewModel" and adding them to observable collection which is source of ItemsControl in the "CodecView"..
so at this point it will generate 2 CodecWidgetViews.. on button click i am adding 4 more instances so it will generate 4 CodecWidgetViews.. You can modify the code in the "mAddGroupBoxCommandExecuted" method as per your requirement..
on Button click
CodecView.XAML
<UserControl>
<UserControl.Resources>
<DataTemplate x:Key="CWDataTemplate">
<StackPanel>
<TextBlock Text="{Binding Description}"/>
<local:CodecWidgetView/>
</StackPanel>
</DataTemplate>
</UserControl.Resources>
<Grid>
<Grid>
<ScrollViewer Name="GroupBoxScroll" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0" >
<Grid Name="NumberofCodecs" Style="{DynamicResource styleBackground}" >
<ItemsControl ItemTemplate="{StaticResource CWDataTemplate}" ItemsSource="{Binding CodecWidgets}"/>
</Grid>
</ScrollViewer>
</Grid>
<Button Content="Add Box" Name="AddBoxBtn" Command="{Binding AddGroupBoxCommand}" Click="AddBoxBtn_Click" HorizontalAlignment="Right" VerticalAlignment="Bottom" />
</Grid>
</UserControl>
CodecViewModel.cs
Create a property like this
public ObservableCollection<CodecWidgetViewModel> CodecWidgets { get; set; }
And add following code to your CodecViewModel constructor
CodecWidgets = new ObservableCollection<CodecWidgetViewModel>();
CodecWidgets.Add(new CodecWidgetViewModel { Description = "Location 1"});
CodecWidgets.Add(new CodecWidgetViewModel { Description = "Location 2" });
To Add widgets
public void mAddGroupBoxCommandExecuted()
{
CodecWidgets.Add(new CodecWidgetViewModel { Description = "Location 3" });
CodecWidgets.Add(new CodecWidgetViewModel { Description = "Location 4" });
CodecWidgets.Add(new CodecWidgetViewModel { Description = "Location 5" });
CodecWidgets.Add(new CodecWidgetViewModel { Description = "Location 6" });
}
Create following class
CodecWidgetViewModel.cs
public class CodecWidgetViewModel
{
private string _description;
public string Description {
get { return _description; }
set {
_description = value;
}
}
}
Related
I'm working on a UWP FTP front-end application. I've created a UserControl that mimics the form of a standard Windows desktop icon (consisting of a StackPanel containing an Image and a TextBlock) which is to be used as a way of displaying saved favorites. What I'd like is for the user to be able to select any image to be used as the icon for each favorite, but have run into some pretty significant issue with getting this to work, I believe due to the Windows 10 "no access to filesystem" restriction--I haven't figured out that part yet.
As a temporary substitution, I came up with the idea of having a set of icons for the user to select from, all stored within the Assets folder of the application. I've created an IconSelector page/child window (IconSelector.xaml) that pops up when appropriate, allowing the user to select from 8 different Images.
The issue I'm running into is getting the selected Image back to the parent window (MainPage.xaml). I thought of just passing an int from child to parent, and then use that int with an enum to indicate the correct image, but I can't figure out how to pass any parameter at all between child and parent.
I did find this question on SO, but it's for Silverlighbt and doesn't seem to work in UWP (unless I implemented it incorrectly).
Does anybody have any idea on how to accomplish this? Code (relevant portions) pasted below:
MainPage XAML
<Canvas Grid.Column="1" Grid.Row="0" Grid.RowSpan="5" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Image Source="Assets\Red.png" Canvas.ZIndex="200" />
<Border x:Name="addFtpGrid" Visibility="Visible" Canvas.Left="300" Canvas.Top="300" Width="600" Height="350" BorderBrush="{ThemeResource SystemControlBackgroundAccentRevealBorderBrush}" BorderThickness="3">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1.5*" />
<ColumnDefinition Width="3*" />
<ColumnDefinition Width="1.5*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Text="Link name" Grid.Column="0" Grid.Row="0" VerticalAlignment="Center" HorizontalAlignment="Right" Margin="5,0" />
<TextBlock Text="Address" Grid.Column="0" Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Right" Margin="5,0" />
<TextBlock Text="Username" Grid.Column="0" Grid.Row="2" VerticalAlignment="Center" HorizontalAlignment="Right" Margin="5,0" />
<TextBlock Text="Password" Grid.Column="0" Grid.Row="3" VerticalAlignment="Center" HorizontalAlignment="Right" Margin="5,0" />
<TextBlock Text="Confirm Password" Grid.Column="0" Grid.Row="4" VerticalAlignment="Center" HorizontalAlignment="Right" Margin="5,0" />
<TextBox x:Name="linkNameEntry" HorizontalAlignment="Stretch" VerticalAlignment="Center" Grid.Column="1" Grid.Row="0" Margin="5,0" />
<TextBox x:Name="addressEntry" Text="ftp://" HorizontalAlignment="Stretch" VerticalAlignment="Center" Grid.Column="1" Grid.Row="1" Margin="5,0" />
<TextBox x:Name="usernameEntry" HorizontalAlignment="Stretch" VerticalAlignment="Center" Grid.Column="1" Grid.Row="2" Margin="5,0" />
<PasswordBox x:Name="passwordEntry" HorizontalAlignment="Stretch" VerticalAlignment="Center" Grid.Column="1" Grid.Row="3" Margin="5,0">
</PasswordBox>
<PasswordBox x:Name="confirmPasswordEntry" HorizontalAlignment="Stretch" VerticalAlignment="Center" Grid.Column="1" Grid.Row="4" Margin="5,0" LostFocus="ConfirmPasswordEntry_LostFocus" />
<Viewbox Grid.Column="2" Grid.Row="0" Grid.RowSpan="4" Margin="5,15,5,0">
<Image x:Name="imageEntry" Source="Assets/SquircleX.png" Tapped="ImageEntry_TappedAsync" />
</Viewbox>
<TextBlock Text="Click image to change" Grid.Column="2" Grid.Row="4" HorizontalAlignment="Center" VerticalAlignment="Center" />
<Button x:Name="saveNewFtpLink" Click="SaveNewFtpLink_Click" Content="Save Changes" Grid.Column="0" Grid.Row="5" Grid.ColumnSpan="3" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,10"/>
</Grid>
</Border>
</Canvas>
MainPage C#
private async void ImageEntry_TappedAsync(object sender, TappedRoutedEventArgs e)
{
IconSelector selector = new IconSelector();
selector.Tapped += new TappedEventHandler(selector_Tapped);
ShowDialog(selector);
//List<string> fileTypes = new List<string> { ".jpg", ".jpeg", ".png", ".bmp", ".gif", ".tiff", ".ico" };
//FileOpenPicker picker = new FileOpenPicker();
//picker.ViewMode = PickerViewMode.Thumbnail;
//picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
//foreach (string type in fileTypes)
//{
// picker.FileTypeFilter.Add(type);
//}
//StorageFile file = await picker.PickSingleFileAsync();
//if(file != null)
//{
// imageEntry.Source = new BitmapImage(new Uri(file.Path));
// Image selectedImage = new Image();
// selectedImage.Source = imageEntry.Source;
// imageEntry = selectedImage;
// imageEntry.UpdateLayout();
// imageToken = StorageApplicationPermissions.FutureAccessList.Add(file);
//}
}
IconSelector XAML
<Page
x:Class="FtpSharp.IconSelector"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:FtpSharp"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignHeight="175" d:DesignWidth="600"
Background="{ThemeResource ContentDialogBackgroundThemeBrush}">
<Page.Resources>
<Style x:Key="selectionStyle" TargetType="Border">
<Setter Property="CornerRadius" Value="10" />
<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="Margin" Value="10,10,5,5" />
<Setter Property="BorderThickness" Value="3" />
</Style>
</Page.Resources>
<Grid VerticalAlignment="Center">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ScrollViewer HorizontalScrollBarVisibility="Auto">
<StackPanel x:Name="iconViewer" Orientation="Horizontal" Width="1100">
<Border Style="{StaticResource selectionStyle}">
<Image Source="Assets\FtpRed.png" Margin="4" Height="96" Tapped="Image_Tapped" />
</Border>
<Border Style="{StaticResource selectionStyle}">
<Image Source="Assets\FtpOrange.png" Margin="4" Height="96" Tapped="Image_Tapped" />
</Border>
<Border Style="{StaticResource selectionStyle}">
<Image Source="Assets\FtpYellow.png" Margin="4" Height="96" Tapped="Image_Tapped" />
</Border>
<Border Style="{StaticResource selectionStyle}">
<Image Source="Assets\FtpGreen.png" Margin="4" Height="96" Tapped="Image_Tapped" />
</Border>
<Border Style="{StaticResource selectionStyle}">
<Image Source="Assets\FtpBlue.png" Margin="4" Height="96" Tapped="Image_Tapped" />
</Border>
<Border Style="{StaticResource selectionStyle}">
<Image Source="Assets\FtpPurple.png" Margin="4" Height="96" Tapped="Image_Tapped" />
</Border>
<Border Style="{StaticResource selectionStyle}">
<Image Source="Assets\FtpPink.png" Margin="4" Height="96" Tapped="Image_Tapped" />
</Border>
<Border Style="{StaticResource selectionStyle}">
<Image Source="Assets\FtpTeal.png" Margin="4" Height="96" Tapped="Image_Tapped" />
</Border>
</StackPanel>
</ScrollViewer>
<Button x:Name="commitSelection" Content="Save" Grid.Row="1" Foreground="Black" HorizontalAlignment="Center" Margin="0,10" />
</Grid>
IconSelector C#
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
namespace FtpSharp
{
public sealed partial class IconSelector : Page
{
private static readonly DependencyProperty SelectedIconProperty = DependencyProperty.Register("SelectedIcon", typeof(int),
typeof(IconSelector), new PropertyMetadata(0));
public int SelectedIcon
{
get { return (int)GetValue(SelectedIconProperty); }
set { SetValue(SelectedIconProperty, value); }
}
public IconSelector()
{
this.InitializeComponent();
}
private void Image_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
{
Image tappedImage = (Image)sender;
Border tappedBorder = (Border)tappedImage.Parent;
SolidColorBrush blue = new SolidColorBrush(Colors.Blue);
foreach (Border border in iconViewer.Children)
{
border.BorderBrush = new SolidColorBrush(Colors.Transparent);
}
tappedBorder.BorderBrush = new SolidColorBrush(Color.FromArgb(255,0,0,255));
}
}
In this case you can either provide the result as a public property of the IconSelector class, or as EventArgs of an event. You already have the SelectedIcon property there, so you can use it. To notify the MainPage that the selection has occurred, you need to add an event to IconSelector - for example DialogCompleted:
public event EventHandler<int> DialogCompleted;
You will trigger this event when the dialog is confirmed by the user:
DialogCompleted?.Invoke(this, SelectedIcon);
Then within MainPage, you need to subscribe to this event:
IconSelector selector = new IconSelector();
selector.DialogCompleted += IconDialogCompleted;
ShowDialog(selector);
And now get the SelectedIcon inside the handler:
private void IconDialogCompleted(object sender, int selectedIcon)
{
//do something with selectedIcon
}
I have an ItemsControl with DataTemplate in my Page.Xaml and the code is like below:
<ItemsControl x:Name="chatUI" VerticalAlignment="Bottom">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid x:Name="myGrid" Width="340" Background="{Binding Background}" HorizontalAlignment="{Binding GridHorizontalAlign}" Margin="10,0,10,10" MinHeight="45" BorderBrush="#FF003A4F" BorderThickness="0,0,0,2">
<Polygon Visibility="{Binding RightVisibility}" Fill="{Binding Background}" Points="0,0 5,6, 0,12" VerticalAlignment="Top" HorizontalAlignment="Right" Margin="0,0,-5,0" />
<Polygon Visibility="{Binding LeftVisibility}" Fill="{Binding Background}" Points="5,0 0,6, 5,12" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="-5,0,0,0" />
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Text="{Binding Text}" TextWrapping="Wrap" FontSize="15" FontFamily="Segoe UI" Foreground="White" Margin="10,10,10,0"/>
<TextBlock Grid.Row="1" Text="{Binding Time}" TextWrapping="Wrap" FontSize="11" FontFamily="Segoe UI" Foreground="LightGray" Margin="10,0,10,5" VerticalAlignment="Bottom" TextAlignment="Right"/>
</Grid>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
What I need right now is getting Text which is bound to the TextBlock when I right click on the grid named myGrid. How is that possible in C#?
We can add the RightTapped event of the Grid, it will be fired when you right click the Grid.
In the RightTapped event we can use Grid.Children to get the collection of child elements of the Grid. That we can get the Grid in the root Grid that named myGrid. That we can use the Grid.Children to get the TextBlock in the Grid.
For example:
private async void myGrid_RightTapped(object sender, RightTappedRoutedEventArgs e)
{
var RightTapGrid = sender as Grid;
var childernElements = RightTapGrid.Children;
foreach (var item in childernElements)
{
var grid = item as Grid;
if (grid != null)
{
var itemchildernElements = grid.Children;
foreach (var text in itemchildernElements)
{
var textBlock = text as TextBlock;
var dialog = new ContentDialog()
{
Title = textBlock.Text,
MaxWidth = this.ActualWidth
};
dialog.PrimaryButtonText = "OK";
dialog.SecondaryButtonText = "Cancel";
await dialog.ShowAsync();
break;
}
}
}
}
If you get your Binding Data from Class called ClassName
You can try this code
XAML:
<ListView x:Name="chatUI" VerticalAlignment="Bottom" SelectionChanged="chatUI_SelectionChanged">
<ListView.ItemTemplate>
<DataTemplate>
<Grid x:Name="myGrid" Width="340" Background="{Binding Background}" HorizontalAlignment="{Binding GridHorizontalAlign}" Margin="10,0,10,10" MinHeight="45" BorderBrush="#FF003A4F" BorderThickness="0,0,0,2">
<Polygon Visibility="{Binding RightVisibility}" Fill="{Binding Background}" Points="0,0 5,6, 0,12" VerticalAlignment="Top" HorizontalAlignment="Right" Margin="0,0,-5,0" />
<Polygon Visibility="{Binding LeftVisibility}" Fill="{Binding Background}" Points="5,0 0,6, 5,12" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="-5,0,0,0" />
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Text="{Binding Text}" TextWrapping="Wrap" FontSize="15" FontFamily="Segoe UI" Foreground="White" Margin="10,10,10,0"/>
<TextBlock Grid.Row="1" Text="{Binding Time}" TextWrapping="Wrap" FontSize="11" FontFamily="Segoe UI" Foreground="LightGray" Margin="10,0,10,5" VerticalAlignment="Bottom" TextAlignment="Right"/>
</Grid>
</Grid>
</DataTemplate>
</Listview.ItemTemplate>
And add SelectionChanged Event :
private void chatUI_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListView view = (ListView)sender;
//Get Selected Item
ClassName class = view.SelectedItem as ClassName;
string path = class.Text;
// Now we have Text of selected item in Listview
}
I have a data input form where i have textboxes,comboboxes and datepickers. I want to Bind comboboxes to the DB column so that users select the correct value for insertion. I have attached the viewmodel class and XAML code. In the viewmodel code "private void GetSW()" - this gets all the list of the entity class and "private void addSW()" this adds the record to the DB, Except the combobox binding everything works fine. in XAML i have binded combobox like this but this give blank combobox, please help what i am missing. I researched many topics on this forum but didn't find any solution
<ComboBox x:Name="PSW" Grid.Column="3" Grid.Row="2" ItemsSource="{Binding newSW.PreviousSW}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="100" Height="20"/>
Its a ViewModel Code
using BusinessEntities;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using MUDB.Services;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace MUDB.Ui.Logic
{
public class SoftwareVersionListViewModel:ViewModelBase
{
private bool enableRowDetails=false;
public bool EnagleRowDetails
{
get { return enableRowDetails; }
set {
enableRowDetails = value;
RaisePropertyChanged();
}
}
public SoftwareVersionListViewModel()
{
SaveSW = new RelayCommand(addSW);
//savecommand = new RelayCommand(addprod);
GetSW();
newSW = new SoftwareDefEntity();
EditSW = new RelayCommand(() => {
EnagleRowDetails = true;
MessageBox.Show("Edit button clicked!!");});
//SWList = new SoftwareDefEntity(); //Initializing the object of the Entity class
}
public List<SoftwareDefEntity> SWentities
{
get;
set;
}
private SoftwareDefEntity _selectedsw;
public SoftwareDefEntity Selectedsw
{
get { return _selectedsw; }
set
{
_selectedsw = value; //This will get all the values of that particular Selected row that are defined in the entity class
EnagleRowDetails = false; //Reset boolean value EnagleRowDetails, so that the selected rowdetails are disabled until Edit button is not clicked.
//ShowView();
}
}
public RelayCommand SaveSW { get; private set; }
public RelayCommand EditSW { get; private set; }
public SoftwareDefEntity newSW { get; private set; }
private void ShowView()
{
//cUSTOM METHODS
}
private void GetSW() // Method that reads the data from the service layer
{
SWDefService obj = new SWDefService();
SWentities = obj.getSW() ; //getSW is the method refered in Service layer
}
private void addSW()
{
SWDefService obj = new SWDefService();
obj.addSW(newSW); //newproduct object will hold the value of the binded control, in XAML its binded like this "{Binding newproduct.ProductName(ProductName is the field name in the entityclass/DB table)}"
newSW = new SoftwareDefEntity();
}
}
}
This is the XAML Code
<UserControl x:Class="MUDB.Ui.CreateSW"
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:MUDB.Ui"
xmlns:converter="clr-namespace:MUDB.Ui.Logic.Converters;assembly=MUDB.Ui.Logic"
xmlns:enums="clr-namespace:MUDB.Ui.Logic.Enums;assembly=MUDB.Ui.Logic"
mc:Ignorable="d" Height="Auto" Width="Auto"
DataContext="{Binding SoftwareVersionList,Source={StaticResource Locator}}" >
<UserControl.Resources>
<converter:RadioButtonToBooleanConverter x:Key="RadioButtonToBooleanConverter" />
</UserControl.Resources>
<Grid>
<Border Background="#90000000" Visibility="{Binding Visibility}">
<Border BorderBrush="Black" BorderThickness="1" Background="White"
CornerRadius="10,0,10,0" VerticalAlignment="Center"
HorizontalAlignment="Center">
<Border.BitmapEffect>
<DropShadowBitmapEffect Color="Black" Opacity="0.5" Direction="270" ShadowDepth="0.7" />
</Border.BitmapEffect>
<Grid Margin="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="200"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="40"/>
<RowDefinition Height="25"/>
<RowDefinition Height="30"/>
<RowDefinition Height="25"/>
<RowDefinition Height="30"/>
<RowDefinition Height="25"/>
<RowDefinition Height="30"/>
<RowDefinition Height="100"/>
<RowDefinition Height="40"/>
<RowDefinition Height="40"/>
<RowDefinition Height="40"/>
</Grid.RowDefinitions>
<Label Content="Create New Software Version" Grid.Column="0" Grid.Row="0" Foreground="White" Background="black"
HorizontalAlignment="Stretch" VerticalAlignment="Center" Grid.ColumnSpan="3" />
<Label Content="ECU" Grid.Column="0" Grid.Row="1" Foreground="Black" HorizontalAlignment="Left"
VerticalAlignment="Bottom" />
<Label Content="Software Name" Grid.Column="1" Grid.Row="1" Foreground="Black" HorizontalAlignment="Left"
VerticalAlignment="Bottom" />
<Label Content="Previous Software" Grid.Column="2" Grid.Row="1" Foreground="Black" HorizontalAlignment="Left"
VerticalAlignment="Bottom" />
<Label Content="Request Freeze Date" Grid.Column="0" Grid.Row="3" Foreground="Black" HorizontalAlignment="Left"
VerticalAlignment="Bottom" />
<Label Content="Request Freeze Status" Grid.Column="1" Grid.Row="3" Foreground="Black" HorizontalAlignment="Left"
VerticalAlignment="Bottom" />
<Label Content="Software Freeze Date" Grid.Column="0" Grid.Row="5" Foreground="Black" HorizontalAlignment="Left"
VerticalAlignment="Center" />
<Label Content="Software Freeze Status" Grid.Column="1" Grid.Row="5" Foreground="Black" HorizontalAlignment="Left"
VerticalAlignment="Center" />
<Label Content="Comments" Grid.Column="0" Grid.Row="7" Foreground="Black" HorizontalAlignment="Left"
VerticalAlignment="Center" />
<ComboBox x:Name="ECU" Grid.Column="0" Grid.Row="2" Text="{Binding newSW.ECU}" Margin="10 0 0 0" HorizontalAlignment="Left" VerticalAlignment="Top" Width="80" Height="Auto">
<ComboBoxItem Name="cbi1">ACM</ComboBoxItem>
<ComboBoxItem Name="cbi2">MCM</ComboBoxItem>
</ComboBox>
<TextBox x:Name="SW" Grid.Column="1" Grid.Row="2" Text="{Binding newSW.SoftwareName}" HorizontalAlignment="Left" VerticalAlignment="Top" Height="Auto" Width="150" />
<ComboBox x:Name="PSW" Grid.Column="3" Grid.Row="2" ItemsSource="{Binding PreviousSW}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="100" Height="20"/>
<DatePicker Grid.Column="0" Grid.Row="4" Margin="10 0 0 0" HorizontalAlignment="Left" VerticalAlignment="top" SelectedDate="{Binding newSW.Req_Freeze_Date}" Height="Auto" Width="Auto"/>
<DatePicker Grid.Column="0" Grid.Row="6" Margin="10 0 0 0" HorizontalAlignment="Left" VerticalAlignment="top" SelectedDate="{Binding newSW.SW_Freeze_Date}" Height="Auto" Width="Auto"/>
<RadioButton Content="Yes" GroupName="ReQstat" IsChecked="{Binding newSW.Req_Freeze_Status, Mode=OneWayToSource, Converter={StaticResource RadioButtonToBooleanConverter}, ConverterParameter={x:Static enums:RadioSelectionEnum.Yes}}" Style="{StaticResource AccentRadioButton}" Grid.Column="1" Grid.Row="4" HorizontalAlignment="Left" VerticalAlignment="Top" Height="14" Width="Auto"/>
<RadioButton Content="No" GroupName="ReQstat" IsChecked="{Binding newSW.Req_Freeze_Status, Mode=OneWayToSource, Converter={StaticResource RadioButtonToBooleanConverter}, ConverterParameter={x:Static enums:RadioSelectionEnum.No}}" Style="{StaticResource AccentRadioButton}" Grid.Column="1" Grid.Row="4" Margin="60 0 0 0" HorizontalAlignment="Left" VerticalAlignment="Top" Height="Auto" Width="Auto"/>
<RadioButton Content="Yes" GroupName="SWstat" IsChecked="{Binding newSW.SW_Freeze_Status, Mode=OneWayToSource, Converter={StaticResource RadioButtonToBooleanConverter}, ConverterParameter={x:Static enums:RadioSelectionEnum.Yes}}" Style="{StaticResource AccentRadioButton}" Grid.Column="1" Grid.Row="6" HorizontalAlignment="Left" VerticalAlignment="Top" Height="Auto" Width="Auto"/>
<RadioButton Content="No" GroupName="SWstat" IsChecked="{Binding newSW.SW_Freeze_Status, Mode=OneWayToSource, Converter={StaticResource RadioButtonToBooleanConverter}, ConverterParameter={x:Static enums:RadioSelectionEnum.No}}" Style="{StaticResource AccentRadioButton}" Grid.Column="1" Grid.Row="6" Margin="60 0 0 0" HorizontalAlignment="Left" VerticalAlignment="Top" Height="Auto" Width="Auto"/>
<TextBox x:Name="CommenttextBox" Grid.Column="1" Grid.Row="7" HorizontalAlignment="Left" Height="69" TextWrapping="WrapWithOverflow" VerticalAlignment="Center" Text="{Binding Comment}" Width="170" Margin="4.4,2.2,0,0" />
<UniformGrid Grid.Row="9" Margin="2" Columns="2" HorizontalAlignment="Stretch"
VerticalAlignment="Center" Height="Auto">
<Button x:Name="SaveButton" Command="{Binding SaveSW}" Content="Save" Height="27" />
<Button x:Name="CloseButton" Click="CloseButton_Click" Content="Close" Height="26" />
</UniformGrid>
</Grid>
</Border>
</Border>
</Grid>
</UserControl>
I guess you want to display the list of SoftwareDefEntity objects in your ComboBox.
Bind to the SWentities property then:
<ComboBox x:Name="PSW" Grid.Column="3" Grid.Row="2" ItemsSource="{Binding SWentities}" DisplayMemberPath="Name" ... />
And raise the PropertyChanged event in its setter of this property:
private List<SoftwareDefEntity> _swEntities;
public List<SoftwareDefEntity> SWentities
{
get { return _swEntities; }
set { _swEntities = value; RaisePropertyChanged(); }
}
This is the code to bind the data to combobox. i did not add any of other controls since those are working fine at your place. Observable collection is easy way to bind combobox .
Here is your View Model..
public class SoftwareVersionListViewModel : ViewModelBase
{
public SoftwareVersionListViewModel()
{
GetSW();
}
//Define the observable collection
private ObservableCollection<SoftwareDefEntity> _SWmappings2 = new ObservableCollection<SoftwareDefEntity>();
//here is your Entity list
public List<SoftwareDefEntity> SWentities
{
get;
set;
}
// Obeservable collection property for access
public ObservableCollection<SoftwareDefEntity> SWmappings2
{
get { return _SWmappings2; }
set
{
_SWmappings2 = value;
OnPropertyChanged("appeventmappings2");
}
}
/// <summary>
/// load the combobox
/// </summary>
private void GetSW() // Method that reads the data from the service layer
{
SWDefService obj = new SWDefService();
SWentities = obj.getSW(); //getSW is the method refered in Service layer
SWentities.ForEach(_SWmappings2.Add);
}
}
and Xaml...
<ComboBox x:Name="ComboBox" ItemsSource="{Binding SWmappings2, UpdateSourceTrigger=PropertyChanged}" DisplayMemberPath="PreviousSW" SelectedItem="{Binding PreviousSW, Mode=TwoWay}" Grid.Row="0" >
</ComboBox>
I am working on silverlight and I am new in it, I have a combox box,inside which I have a checkbox and textbox. I want to get the value of these controls on button click, How can I do this in SilverLight?
This is my ComboBox
<ComboBox x:Name="Type" VerticalAlignment="Top" Margin="2,8,-2,0" Grid.ColumnSpan="3" Height="28" Padding="3">
<ComboBoxItem>
<Grid HorizontalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="*" MinWidth="105" />
<ColumnDefinition Width="60" />
</Grid.ColumnDefinitions>
<CheckBox IsChecked="true" VerticalAlignment="Center" Grid.Column="0"/>
<TextBlock Text="All" VerticalAlignment="Center" Grid.Column="1" Style="{x:Null}" FontSize="11"/>
</Grid>
</ComboBoxItem>
<ComboBoxItem>
<Grid HorizontalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="*" MinWidth="105" />
<ColumnDefinition Width="60" />
</Grid.ColumnDefinitions>
<CheckBox IsChecked="true" VerticalAlignment="Center" Grid.Column="0"/>
<TextBlock Text="General" VerticalAlignment="Center" Grid.Column="1" Style="{x:Null}" FontSize="11"/>
<TextBox Text="25" VerticalAlignment="Center" Grid.Column="2" FontSize="11" Padding="2" HorizontalContentAlignment="Right"/>
</Grid>
</ComboBoxItem>
</ComboBox>
User have option to select multiple values
I am using MVVM pattern
Since all of your ComboBox Items are unchanging, you can give Names to those items and reference them directly.
<ComboBoxItem x:Name="ComboItemAll">
...
</ComboBoxItem>
<ComboBoxItem x:Name="ComboItemGeneral">
...
</ComboBoxItem>
and the in the Button Click event:
if (ComboItemAll.IsSelected)
{
...
}
else if (ComboItemGeneral.IsSelected)
{
...
}
alternatively, you could also get this information from your ComboBox "Type":
var selectedItem = Type.SelectedItem;
if (selectedItem.Name.StartsWith("ComboItemAll"))
{
...
}
else if (selectedItem.Name.StartsWith("ComboItemGeneral"))
{
...
}
For MVVM (Edit):
Xaml (View):
<ComboBox SelectedItem="{Binding SelectedCustomItem, Mode=TwoWay}" ItemsSource="{CustomItems}" ItemTemplate={StaticResource CustomItemsTemplate} />
Xaml (Resource):
<DataTemplate x:Key="CustomItemsTemplate">
<StackPanel
<CheckBox IsChecked="{Binding IsSelected}" VerticalAlignment="Center"/>
<TextBlock Text="{Binding CustomPropertyFromCustomClass}"/>
</StackPanel>
</DataTemplate>
VM:
public class ViewModel
{
public ViewModel()
{
CustomItems = new ObservableCollection<CustomClass>();
CustomItems.Add(new CustomClass() { "All" });
CustomItems.Add(new CustomClass() { "General" });
}
private ObservableCollection<CustomClass> customItems = null;
public ObservableCollection<CustomClass> CustomItems
{
get { return customItems; }
set
{
if (object.Equals(value, customItems) == false)
{
customItems = value;
OnPropertyChanged(() => CustomItems);
}
}
}
private CustomClass selectedCustomItem = null;
public CustomClass SelectedCustomItem
{
get { return selectedCustomItem; }
set
{
if (object.Equals(value, selectedCustomItem) == false)
{
selectedCustomItem= value;
OnPropertyChanged(() => SelectedCustomItem);
}
}
}
}
You should never reference your combobox directly from the ViewModel. Everything in your ViewModel should be related to data manipulation and know nothing of the View (aka ComboBox).
Everything else should be done in the view. If you need to access the ComboBox, you need you ask yourself why, and can I do that logic in the XAML through templates and bindings?
Well i don't know what to do else. I've checked in the code and everything it's looking fine.
So my problem is that the combo box isn't populated with any data, I've checked the ObservableCollection set and it has the data but it isn't any popualted
I used the MVVM pattern and everything goes well but the GET isn't called
Could i get some tip what could be the cause, because i'm out of ideas
StudentDetailView.xaml
<Grid x:Name="LayoutRoot" Background="White">
<Grid DataContext="{Binding}" HorizontalAlignment="Left" Margin="12,12,0,0" Name="grid1" VerticalAlignment="Top" Height="176" Width="376">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="31*" />
</Grid.RowDefinitions>
<sdk:Label Content="Clasa ID:" Grid.Column="0" Grid.Row="0" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
<ComboBox Grid.Column="1" Grid.Row="0" Height="23" HorizontalAlignment="Left" Margin="3"
Name="clasaIDComboBox" VerticalAlignment="Center" Width="120"
DisplayMemberPath="Nume"
SelectedValuePath="ID" />
<sdk:Label Content="Data Nasterii:" Grid.Column="0" Grid.Row="1" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
<sdk:DatePicker Grid.Column="1" Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="3" Name="data_NasteriiDatePicker" VerticalAlignment="Center" Width="120" />
<sdk:Label Content="ID:" Grid.Column="0" Grid.Row="2" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
<TextBox Grid.Column="1" Grid.Row="2" Height="23" HorizontalAlignment="Left" Margin="3" Name="iDTextBox" VerticalAlignment="Center" Width="120" />
<sdk:Label Content="Liceu ID:" Grid.Column="0" Grid.Row="3" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
<TextBox Grid.Column="1" Grid.Row="3" Height="23" HorizontalAlignment="Left" Margin="3" Name="liceuIDTextBox" VerticalAlignment="Center" Width="120" />
<sdk:Label Content="Nume:" Grid.Column="0" Grid.Row="4" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
<TextBox Grid.Column="1" Grid.Row="4" Height="23" HorizontalAlignment="Left" Margin="3" Name="numeTextBox" VerticalAlignment="Center" Width="120" />
</Grid>
<Button Content="Save Student" Height="23" HorizontalAlignment="Left" Margin="194,232,0,0" Name="btnSaveStudent" VerticalAlignment="Top" Width="95" Click="btnSaveStudent_Click" />
<Button Content="Cancel" Height="23" HorizontalAlignment="Left" Margin="295,232,0,0" Name="btnCancelStudent" VerticalAlignment="Top" Width="75" Click="btnCancelStudent_Click" />
<ct:ValidationSummary Width="300" Margin="12,194,70,23" />
</Grid>
StudentDetailView.xaml.cs
public StudentDetailView()
{
InitializeComponent();
clasaIDComboBox.SetBinding(ComboBox.ItemsSourceProperty, new Binding() { Path = new PropertyPath("LstHighSchool"), Mode = BindingMode.TwoWay });
clasaIDComboBox.SetBinding(ComboBox.SelectedValueProperty, new Binding() { Path = new PropertyPath("SelectedHighSchool"), Mode = BindingMode.TwoWay, NotifyOnValidationError = true, ValidatesOnExceptions = true });
}
And partial code from StudentViewModel.cs
private void AddNewStudentView(object param)
{
StudentDetailView addNewStudentView = new StudentDetailView();
addNewStudentView.DataContext = new Student();
var sdfsdfj = new StudentViewModel();
LoadOperation<Liceu> li = DomainContext.Load(DomainContext.GetLiceusQuery());
li.Completed += (s, e) =>
{
LstHighSchool = (s as LoadOperation<Liceu>).Entities.ToObservableCollection();
};
addNewStudentView.Closed += delegate
{
if (addNewStudentView.DialogResult == true)
{
Student newStudent = addNewStudentView.DataContext as Student;
if (string.IsNullOrEmpty(newStudent.Nume))
{
newStudent.ValidationErrors.Add(new ValidationResult("Numele nu poate sa fie invalid",new string[]{"Nume"}));
}
if (!newStudent.LiceuID.HasValue)
{
newStudent.ValidationErrors.Add(new ValidationResult("Liceu ID este gol", new string[] { "LiceuID" }));
}
if (!newStudent.HasValidationErrors)
{
if (newStudent != null)
{
DomainContext.Students.Add(newStudent);
LstStudents.Add(newStudent);
}
}
else
{
addNewStudentView.Show();
}
}
};
addNewStudentView.Show();
OnPropertyChanged("LstHighSchool");
}
private bool CanWork(object param)
{
return true; //for the moment this remains true, cause you can add all the time a new student, but this can be changed if there must be some conditions
}
private ObservableCollection<Liceu> _lstHighSchool;
public ObservableCollection<Liceu> LstHighSchool
{
get
{
return _lstHighSchool;
}
set
{
_lstHighSchool = value;
OnPropertyChanged("LstHighSchool");
}
}
private int _selectedHighSchool;
public int SelectedHighSchool
{
get
{
return _selectedHighSchool;
}
set
{
_selectedHighSchool = value;
OnPropertyChanged("SelectedHighSchool");
}
}
#endregion
Firstly, Get rid of the Grid DataContext="{Binding}" and then your combobox in the xaml should look like:
<ComboBox Grid.Column="1" Grid.Row="0" Height="23" HorizontalAlignment="Left" Margin="3"
VerticalAlignment="Center" Width="120" DisplayMemberPath="Nume"
SelectedValuePath="ID" ItemsSource="{Binding LstHighSchool}"
SelectedValue="{Binding SelectedHighSchool}" />
Secondly, your code behind for the View should look like,
public StudentDetailView()
{
InitializeComponent();
this.DataContext= new StudentViewModel();
}
Lastly, in the StudentViewModel.cs there should be a property called LstHighSchool which looks fine.