Basically, I'm trying to take information entered by the user on one page and print it out to another page via a "printer friendly" version, or report, of something. I have a MainPage.xaml that is, as the name suggests, my main page, but in a window there is the subpage AdCalculator.xaml where the user enters the information and PrintEstimate.xaml that is navigated to via a button on AdCalculator.
I would like to be able to transfer the information entered in the textboxes from AdCalculator and print it out via text blocks in PrintEstimate. So in order to do that I have the following code:
Views.AdCalculator AdCalc = new Views.AdCalculator();
string PrintCompanyName = AdCalc.CompanyName;
string PrintContactName = AdCalc.txt_CustomerName.Text;
string PrintBillingAddress1 = AdCalc.txt_BillingAddress.Text;
string PrintBillingAddress2 = AdCalc.txt_BillingAddressLine2.Text;
string PrintPhoneNumber = AdCalc.txt_PhoneNumber.Text;
string PrintNumOfAds = AdCalc.txt_NumofAds.Text;
string PrintRateOfPlay = AdCalc.Cmb_Rate.SelectedValue.ToString();
string PrintNumOfMonths = AdCalc.txt_NumofMonths.Text;
string PrintTotalDue = AdCalc.txt_InvoiceSummary_TotalDue.Text;
PrintEstimate PrintEstimatePage = new PrintEstimate();
PrintEstimatePage.txt_CompanyName.Text = PrintCompanyName;
PrintEstimatePage.txt_CustomerName.Text = PrintContactName;
PrintEstimatePage.txt_BillingAddress.Text = PrintBillingAddress1;
PrintEstimatePage.txt_BillingAddressLine2.Text = PrintBillingAddress2;
PrintEstimatePage.txt_PhoneNumber.Text = PrintPhoneNumber;
PrintEstimatePage.txt_InvoiceSummary_NumofAds.Text = PrintNumOfAds;
PrintEstimatePage.txt_InvoiceSummary_RateofPlay.Text = PrintRateOfPlay;
PrintEstimatePage.txt_InvoiceSummary_NumOfMonths.Text = PrintNumOfMonths;
PrintEstimatePage.txt_EstimateTotal.Text = PrintTotalDue;
Only problem is, when I instantiate the new AdCalculator page, it clears the values, so nothing is actually retained as far as user-input goes. Following a lead from a colleague, I believe all I need to do is change the line
Views.AdCalculator AdCalc = new Views.AdCalculator();
to
Views.AdCalculator AdCalc = (AdCalculator)Application.OpenForms["AdCalculator"];
except the "Apllication.OpenForms" doesn't register. I know there are a lot of differences in the way C# code-behind is laid out for silverlight applications, so I didn't know if there was an equivalent that anyone knew about to "Application.OpenForms" that would help solve my issue or if there was any other way to go about getting my task done.
If I understand your question correctly you simply want to get some user input and display it.
I suggest you start by defining a class that will represent the data you are inputting,
for example:
public class Customer
{
public string ContectName { get; set; }
public string BillingAddress1 { get; set; }
public string BillingAddress2 { get; set; }
public string PhoneNumber { get; set; }
public int NumOfAds { get; set; }
public double RateOfPlay { get; set; }
public int NumOfMonths { get; set; }
public double TotalDue { get; set; }
}
On the page where the user inputs data you then create an instance
of this class, either by manually creating an instance and setting
its properties when the user submits (similar to what you are doing in your code)
or use databinding to your advantage (which is what I prefer).
Let's say for example you are inputting data on your MainPage
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
this.DataContext = new Customer();
}
Now you can bind the controls. Let's say you're using a grid:
<Grid x:Name="LayoutRoot" Background="White">
<Grid>
<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="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<sdk:Label Content="Billing Address 1:" Grid.Column="0" Grid.Row="0" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
<TextBox Grid.Column="1" Grid.Row="0" Height="23" HorizontalAlignment="Left" Margin="3" Name="billingAddress1TextBox" Text="{Binding Path=BillingAddress1, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />
<sdk:Label Content="Billing Address 2:" Grid.Column="0" Grid.Row="1" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
<TextBox Grid.Column="1" Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="3" Name="billingAddress2TextBox" Text="{Binding Path=BillingAddress2, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />
<sdk:Label Content="Contect Name:" 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="contectNameTextBox" Text="{Binding Path=ContectName, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />
<sdk:Label Content="Num Of Ads:" 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="numOfAdsTextBox" Text="{Binding Path=NumOfAds, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />
<sdk:Label Content="Num Of Months:" 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="numOfMonthsTextBox" Text="{Binding Path=NumOfMonths, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />
<sdk:Label Content="Phone Number:" Grid.Column="0" Grid.Row="5" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
<TextBox Grid.Column="1" Grid.Row="5" Height="23" HorizontalAlignment="Left" Margin="3" Name="phoneNumberTextBox" Text="{Binding Path=PhoneNumber, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />
<sdk:Label Content="Rate Of Play:" Grid.Column="0" Grid.Row="6" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
<TextBox Grid.Column="1" Grid.Row="6" Height="23" HorizontalAlignment="Left" Margin="3" Name="rateOfPlayTextBox" Text="{Binding Path=RateOfPlay, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />
<sdk:Label Content="Total Due:" Grid.Column="0" Grid.Row="7" HorizontalAlignment="Left" Margin="3" VerticalAlignment="Center" />
<TextBox Grid.Column="1" Grid.Row="7" Height="23" HorizontalAlignment="Left" Margin="3" Name="totalDueTextBox" Text="{Binding Path=TotalDue, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />
</Grid>
</Grid>
When the user clicks the submit button, you can use something like this:
private void Button_Click(object sender, RoutedEventArgs e)
{
var currentCustomer = this.DataContext as Customer;
var previewWindow = new PrintPreviewWindow(currentCustomer);
previewWindow.Show();
}
For this to work you'll need to have a Silverlight ChildWindow like this:
public partial class PrintPreviewWindow : ChildWindow
{
public PrintPreviewWindow(Customer customer)
{
InitializeComponent();
this.DataContext = customer;
}
private void OKButton_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = true;
}
private void CancelButton_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = false;
}
}
So your MainPage creates a new instance of the PrintPreviewChildWindow (could be a page as well if you prefer) and passes along the customer instance. The ChildWindow can then do whatever it wants with it. When the ChildWindow closes, you'll probably want to empty the input page, you can do this by simply setting the data context again:
this.DataContext = new Customer();
I'm guessing this is what you are looking for.
Try to get into the whole data binding stuff, it will save you lots and lots of lines of code. And let us know if this answers your question or if you have more :-)
Related
So I have an audio in WAV format https://youtu.be/nunJDdIlnnk but for some reason, I cannot get it to paste all the transcription in the Textbox, However in the method SpeechRecognizer_Recognizing I can see on my debug windows, that everything is being recognized as the woman speaks.
var config = SpeechConfig.FromSubscription(KEY, Region);
MessageBox.Show("Ready to use speech service in " + config.Region);
// Configure voice
config.SpeechSynthesisVoiceName = "en-US-AriaNeural";
// Configure speech recognition
var taskCompleteionSource = new TaskCompletionSource<int>();
using var audioConfig = AudioConfig.FromWavFileInput(FilePath);
using var speechRecognizer = new SpeechRecognizer(config, audioConfig);
speechRecognizer.Recognizing += SpeechRecognizer_Recognizing;
speechRecognizer.Recognized += SpeechRecognizer_Recognized;
speechRecognizer.SessionStarted += SpeechRecognizer_SessionStarted;
speechRecognizer.SessionStopped += SpeechRecognizer_SessionStopped;
await speechRecognizer.StartContinuousRecognitionAsync().ConfigureAwait(false);
// Waits for completion.
// Use Task.WaitAny to keep the task rooted.
Task.WaitAny(new[] { taskCompleteionSource.Task });
await speechRecognizer.StopContinuousRecognitionAsync().ConfigureAwait(false);
}
private void SpeechRecognizer_SessionStopped(object? sender, SessionEventArgs e)
{
Debug.WriteLine("Stopped");
}
private void SpeechRecognizer_SessionStarted(object? sender, SessionEventArgs e)
{
Debug.WriteLine("Started");
}
private void SpeechRecognizer_Recognized(object? sender, SpeechRecognitionEventArgs e)
{
var transcriptionStringBuilder = new StringBuilder();
if (e.Result.Reason == ResultReason.RecognizedSpeech)
{
transcriptionStringBuilder.Append(e.Result.Text);
Text = transcriptionStringBuilder.ToString(); // This will be the text, that is displayed on textbox
IsVisible = Visibility.Visible;
}
}
private void SpeechRecognizer_Recognizing(object? sender, SpeechRecognitionEventArgs e)
{
Debug.WriteLine("Recogizing: " + e.Result.Text);
}
Output window
This is my XAML code for the UI
<Border Background="#272537"
CornerRadius="20">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="75" />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Text="Transcribe Me"
Foreground="White"
Margin="10,0,0,0"
FontSize="23"
VerticalAlignment="Center" />
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition />
<RowDefinition Height="30" />
</Grid.RowDefinitions>
<syncfusion:SfHubTile Background="#FF1FAEFF">
<behaviors:Interaction.Triggers>
<behaviors:EventTrigger EventName="Click">
<behaviors:InvokeCommandAction Command="{Binding AzureCommand}"
CommandParameter="Audio" />
</behaviors:EventTrigger>
</behaviors:Interaction.Triggers>
<iconPacks:PackIconMaterial Kind="Music" Width="120"
Height="120"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Foreground="White" />
</syncfusion:SfHubTile>
<syncfusion:SfHubTile Grid.Column="1">
<syncfusion:SfHubTile.Header>
<TextBlock Text="Document"
Foreground="White"
FontSize="18"
FontStyle="Oblique" />
</syncfusion:SfHubTile.Header>
<syncfusion:SfHubTile.Title>
<TextBlock Text="Translate"
Foreground="White"
FontSize="18"
HorizontalAlignment="Center"
FontStyle="Oblique" />
</syncfusion:SfHubTile.Title>
<behaviors:Interaction.Triggers>
<behaviors:EventTrigger EventName="Click">
<behaviors:InvokeCommandAction Command="{Binding AzureCommand}"
PassEventArgsToCommand="True"
CommandParameter="Document" />
</behaviors:EventTrigger>
</behaviors:Interaction.Triggers>
</syncfusion:SfHubTile>
<TextBox Grid.Row="1"
IsReadOnly="True"
TextWrapping="Wrap"
Visibility="{Binding IsVisible}"
Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}"
AcceptsReturn="True"
Grid.ColumnSpan="2"
Margin="10" />
<Button Grid.Column="1"
Grid.Row="2"
Visibility="{Binding IsVisible}"
Content="Copy"
Command="{Binding CopyCommand}"
Foreground="White"
FontWeight="Black"
VerticalAlignment="Center"
Margin="0,0,10,10">
</Button>
</Grid>
</Grid>
</Border>
When I run the code, my text box only has the last part of the of the video, witch is "Do I look alright"
The problem was, that I was puttingin my textbox every single sentence that she said.
What you have to do, is to capture everything in the STOPPED method, and probably use a list of chars, loop thru every char, and crate a stringbulder, because using str += item, will create a string every time and is less efficient.
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 have a ListBox which I add items to. Each time i select an item which is an object of a Person this person properties should be showed in textboxes. This person have person properties like age, name, sex and so on.
my listbox selection changed event only triggers one time or on new added items. It doesn't trigger when i click and an that is not just added.
Mainwindow.xaml.cs
namespace GUI_WPF_Eksamen
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
Backlog bl = new Backlog();
public MainWindow()
{
InitializeComponent();
DataContext = bl;
this.PriorityComboBox.Items.Add("High");
this.PriorityComboBox.Items.Add("Medium");
this.PriorityComboBox.Items.Add("Low");
}
private void AddToProductBackLogBtn_Click(object sender, RoutedEventArgs e)
{
this.ProductBacklogList.Items.Add(bl);
this.NameTextBox.Text = String.Empty;
}
private void ProductBacklogList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var item = this.ProductBacklogList.SelectedItem as Backlog;
this.NameLabel.Content = item.NAME;
this.DescriptionTextBlock.Text = item.DESCRIPTION;
this.PriorityLabel.Content = item.PRIORITY;
this.TimeLabel.Content = item.TIME;
}
private void AddToSprint_Click(object sender, RoutedEventArgs e)
{
var currentItem = this.ProductBacklogList.SelectedItem as Backlog;
this.SprintBacklogList.Items.Add(currentItem);
}
}
}
Mainwindow.xaml
<Window x:Class="GUI_WPF_Eksamen.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:GUI_WPF_Eksamen"
Title="GUI WPF application" Height="800" Width="1200">
<Window.Background>
<ImageBrush ImageSource="Images/chalkboard.jpg"/>
</Window.Background>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="69*"/>
<RowDefinition Height="700*"/>
</Grid.RowDefinitions>
<Label x:Name="Title" Content="SCRUM-BOARD XXL" HorizontalAlignment="Center" HorizontalContentAlignment="Center" Margin="15,10,5,0" VerticalAlignment="Top" Width="1172" Height="56" FontSize="36" FontStyle="Italic" FontWeight="Bold" Foreground="White"/>
<Grid HorizontalAlignment="Left" Height="680" Margin="15,10,0,0" Grid.Row="1" VerticalAlignment="Top" Width="354">
<Grid.RowDefinitions>
<RowDefinition Height="94*"/>
<RowDefinition Height="44*"/>
<RowDefinition Height="131*"/>
<RowDefinition Height="53*"/>
<RowDefinition Height="40*"/>
<RowDefinition Height="46*"/>
<RowDefinition Height="272*"/>
</Grid.RowDefinitions>
<Label Content="Navn" HorizontalAlignment="Left" Margin="0,44,0,0" VerticalAlignment="Top" Width="77" FontSize="16" Foreground="White"/>
<Label Content="Beskrivelse
" HorizontalAlignment="Left" Margin="0,10,0,0" VerticalAlignment="Top" Foreground="White" FontSize="16" Height="31" Grid.Row="1"/>
<Label Content="Prioritet" HorizontalAlignment="Left" Margin="0,7,0,0" VerticalAlignment="Top" Width="67" FontSize="16" Foreground="White" Grid.Row="3"/>
<Label Content="Estimeret tidsforbrug" HorizontalAlignment="Left" Margin="0,10,0,0" VerticalAlignment="Top" Foreground="White" FontSize="16" Grid.Row="4" Grid.RowSpan="2"/>
<TextBox x:Name="NameTextBox" HorizontalAlignment="Left" Height="23" Margin="51,52,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="303" Opacity="0.5" Text="{Binding Path=NAME}"/>
<ComboBox x:Name="PriorityComboBox" HorizontalAlignment="Left" Margin="73,12,0,0" VerticalAlignment="Top" Width="152" RenderTransformOrigin="0.5,0.5" Opacity="0.5" Grid.Row="3" SelectedItem="{Binding Path=PRIORITY}">
<ComboBox.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform Angle="0.036"/>
<TranslateTransform/>
</TransformGroup>
</ComboBox.RenderTransform>
</ComboBox>
<TextBox x:Name="TimeTextBox" HorizontalAlignment="Left" Height="23" Margin="0,6,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="204" Opacity="0.5" Grid.Row="5" Text="{Binding Path=TIME}"/>
<Label Content="time(r)" HorizontalAlignment="Left" Margin="209,38,0,0" VerticalAlignment="Top" Foreground="White" FontSize="16" Width="57" Grid.Row="4" Grid.RowSpan="2"/>
<TextBox x:Name="DescriptionTextBox" HorizontalAlignment="Left" Height="111" Margin="0,10,0,0" Grid.Row="2" TextWrapping="Wrap" VerticalAlignment="Top" Width="354" Opacity="0.5" Text="{Binding Path=DESCRIPTION}"/>
<Button x:Name="AddToProductBackLogBtn" Content="Add Backlog item" HorizontalAlignment="Left" Grid.Row="6" VerticalAlignment="Top" Width="200" Height="27" Margin="66,0,0,0" Background="White" Opacity="0.7" Click="AddToProductBackLogBtn_Click"/>
</Grid>
<Grid HorizontalAlignment="Left" Height="680" Margin="374,10,0,0" Grid.Row="1" VerticalAlignment="Top" Width="808" RenderTransformOrigin="0.459,0.431">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="79*"/>
<ColumnDefinition Width="47*"/>
<ColumnDefinition Width="76*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="209*"/>
<RowDefinition Height="131*"/>
</Grid.RowDefinitions>
<Label Content="Navn" HorizontalAlignment="Left" Margin="10,10,0,0" Grid.Row="1" VerticalAlignment="Top" FontSize="16" Foreground="White" Height="31" Width="47"/>
<Label Content="Beskrivelse" HorizontalAlignment="Left" Margin="10,55,0,0" Grid.Row="1" VerticalAlignment="Top" Foreground="White" FontSize="16" Height="31" Width="87"/>
<Label Content="Prioritet
" HorizontalAlignment="Left" Margin="10,10,0,0" Grid.Row="1" VerticalAlignment="Top" Foreground="White" FontSize="16" Height="32" Grid.Column="1" Width="66"/>
<Label Content="Estimeret tidsforbrug" Grid.Column="1" HorizontalAlignment="Left" Margin="10,55,0,0" Grid.Row="1" VerticalAlignment="Top" Foreground="White" FontSize="16" Height="31" Width="159"/>
<Label x:Name="PriorityLabel" Content="" Grid.Column="1" HorizontalAlignment="Left" Margin="90,10,0,0" Grid.Row="1" VerticalAlignment="Top" FontSize="16" Foreground="White" Width="79" Height="31"/>
<Label x:Name="TimeLabel" Grid.Column="2" HorizontalAlignment="Left" Margin="10,55,0,0" Grid.Row="1" VerticalAlignment="Top" Foreground="White" FontSize="16" Width="208" Height="31"/>
<ListBox x:Name="ProductBacklogList" HorizontalAlignment="Left" Height="353" Margin="10,55,0,0" VerticalAlignment="Top" Width="292" DisplayMemberPath="NAME" Opacity="0.505" SelectionChanged="ProductBacklogList_SelectionChanged" RenderTransformOrigin="0.5,0.5">
<ListBox.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform AngleY="-0.195"/>
<RotateTransform/>
<TranslateTransform Y="-0.497"/>
</TransformGroup>
</ListBox.RenderTransform>
</ListBox>
<ListBox x:Name="SprintBacklogList" HorizontalAlignment="Left" Height="353" Margin="10,55,0,0" VerticalAlignment="Top" Width="284" DisplayMemberPath="NAME" Grid.Column="2" Opacity="0.5"/>
<Label x:Name="NameLabel" HorizontalAlignment="Left" Margin="62,14,0,0" Grid.Row="1" VerticalAlignment="Top" Width="244" Height="27" Content="{Binding Path=NAME}" Foreground="White"/>
<Button x:Name="AddToSprint" Content="Add >>" Grid.Column="1" HorizontalAlignment="Left" Margin="54,201,0,0" VerticalAlignment="Top" Width="75" Height="20" Opacity="0.7" Click="AddToSprint_Click"/>
<TextBlock x:Name="DescriptionTextBlock" HorizontalAlignment="Left" Margin="10,86,0,0" Grid.Row="1" TextWrapping="Wrap" VerticalAlignment="Top" Height="166" Width="296" Foreground="White"/>
</Grid>
</Grid>
That way of selection changed can be accomplished easily:
Have a look here:
<Window x:Class="ListBoxSelection.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<DockPanel>
<ListBox ItemsSource="{Binding persons}" IsSynchronizedWithCurrentItem="True" DockPanel.Dock="Top">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" Margin="5,0"/>
<TextBlock Text="{Binding Age, StringFormat=is {0} years old}" Margin="5,0"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<StackPanel Orientation="Horizontal" DataContext="{Binding persons}" DockPanel.Dock="Top">
<TextBlock Text="You have selected: " FontWeight="SemiBold"/>
<TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}"
Margin="5,0"
FontWeight="SemiBold"
VerticalAlignment="Top"
HorizontalAlignment="Center"/>
<TextBox Text="{Binding Age, UpdateSourceTrigger=PropertyChanged}"
Margin="5,0"
FontWeight="SemiBold"
VerticalAlignment="Top"
HorizontalAlignment="Left"/>
</StackPanel>
<Button Content="Add Item" DockPanel.Dock="Top" Width="60" VerticalAlignment="Top" Margin="20" Click="btnAddItem_Click"/>
</DockPanel>
Note this down: IsSynchronizedWithCurrentItem="True"
From MSDN:
Gets or sets a value that indicates whether a Selector should keep the
SelectedItem synchronized with the current item in the Items property.
What's the next step? Display the selected item:
<StackPanel DataContext="{Binding persons}"/>
StackPanel is not an ItemsControl, it will not try to display all the items in persons but instead it will look for the selected one.
The ICollectionView interface contains a member called CurrentItem. What the IsSynchronizedWithCurrentItem does is: whenever an item is clicked on the ItemsControl, it sets the CurrentItem for the collection view. The ICollectionView also has two events: CurrentItemChanging and CurrentItemChanged. When the IsSynchronizedWithCurrentItem property is set, the ItemsControl will update the SelectedItem based on what the ICollectionView's CurrentItem is.
Further more, using UpdateSourceTrigger=PropertyChanged you will be able to update you selected item and this will be immediately displayed in the ListBox.
OK, that's about, here is the rest of the code:
public class Person : INotifyPropertyChanged
{
private string _Name;
public string Name
{
get { return _Name; }
set
{
_Name = value;
PropertyChanged(this, new PropertyChangedEventArgs("Name"));
}
}
private int _Age;
public int Age
{
get { return _Age; }
set
{
_Age = value;
PropertyChanged(this, new PropertyChangedEventArgs("Age"));
}
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
}
And the codebehind:
public partial class MainWindow : Window
{
public ObservableCollection<Person> persons { get; set; }
public Person SelectedPerson
{
get { return (Person)GetValue(SelectedPersonProperty); }
set { SetValue(SelectedPersonProperty, value); }
}
// Using a DependencyProperty as the backing store for SelectedPerson. This enables animation, styling, binding, etc...
public static readonly DependencyProperty SelectedPersonProperty =
DependencyProperty.Register("SelectedPerson", typeof(Person), typeof(MainWindow), new PropertyMetadata(null));
public MainWindow()
{
InitializeComponent();
persons = new ObservableCollection<Person>();
persons.Add(new Person() { Name = "Name1", Age = 20 });
persons.Add(new Person() { Name = "Name2", Age = 25 });
persons.Add(new Person() { Name = "Name3", Age = 30 });
this.DataContext = this;
}
private void btnAddItem_Click(object sender, RoutedEventArgs e)
{
persons.Add(new Person() { Name = "NameAdded", Age = 50 });
}
}
As you see, your SelectionChanged handler is not needed anymore.
You may be asking, what is that SelectedPerson in the code behind:
Add this binding on the ListBox:
SelectedItem="{Binding SelectedPerson}"
And in that AddToSprint_Click use the SelectedPerson to get the Person instead of directly accessing the ListBox.
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.
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;
}
}
}