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>
Related
I want to assign the values of the findFamily object to the different TextBox(s) i tried the following code but it's not working would you please suggest me a better way. Thanks in advance.
private void Search_Click(object sender, RoutedEventArgs e)
{
if (SearchFamilyMemberId.Text.Trim() != "")
{
SITDataDataContext con = new SITDataDataContext();
List<Family> findFamily = (from s in con.Families where s.FamilyMemberId.Equals(SearchFamilyMemberId.Text.Trim()) select s).ToList();
if (findFamily.Any())
{
FamilyMemberId.Text = findFamily[0];
FirstName.Text = findFamily[1];
LastName.Text = findFamily[2];
if (findFamily[3]=="Male")
{
Male.IsChecked = true;
}
else
{
Female.IsChecked = true;
}
Phone.Text = findFamily[4];
Address.Text = findFamily[5];
}
else
{
MessageBox.Show("Family Id not found!");
}
}
else
{
MessageBox.Show("Invalid Id!");
}
}
here is my xamal code
<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Label Grid.Row="1" Grid.Column="0" Content="Family Member ID:"/>
<Label Grid.Row="2" Grid.Column="0" Content="First Name:"/>
<Label Grid.Row="3" Grid.Column="0" Content="Last Name:"/>
<Label Grid.Row="4" Grid.Column="0" Content="Gender:"/>
<Label Grid.Row="5" Grid.Column="0" Content="Phone:"/>
<Label Grid.Row="6" Grid.Column="0" Content="Address:"/>
<CheckBox Name="ColonyResident" Content="Colony Resident" Grid.Row="0" Grid.Column="0" Margin="5" Checked="ColonyResident_Checked" Unchecked="ColonyResident_Unchecked"/>
<TextBox Name="SearchFamilyMemberId" IsEnabled="False" SelectionChanged="FamilyMemberId_SelectionChanged" Grid.Row="0" Grid.Column="1" Margin="3"/>
<TextBox Name="FamilyMemberId" IsEnabled="False" Grid.Row="1" Grid.Column="1" Margin="3" Grid.ColumnSpan="2"/>
<TextBox Name="FirstName" Grid.Row="2" Grid.Column="1" Margin="3" Grid.ColumnSpan="2"/>
<TextBox Name="LastName" Grid.Row="3" Grid.Column="1" Margin="3" Grid.ColumnSpan="2"/>
<RadioButton Name="Male" Grid.Row="4" Grid.Column="1" Margin="3" Content="Male" />
<RadioButton Name="Female" Grid.Row="4" Grid.Column="2" Margin="3" Content="Female" />
<TextBox Name="Phone" Grid.Row="5" Grid.Column="1" Margin="3" Grid.ColumnSpan="2"/>
<TextBox Name="Address" Grid.Row="6" Grid.Column="1" Margin="3" Grid.ColumnSpan="2" TextWrapping="Wrap"/>
<Button Name="Search" IsEnabled="False" Grid.Row="0" Grid.Column="2" Margin="3" MinWidth="100" MinHeight="25" HorizontalAlignment="Center" Content="Search" Click="Search_Click"/>
<Button IsDefault="True" Grid.Row="7" Grid.Column="1" Margin="3" MinWidth="100" MinHeight="25" HorizontalAlignment="Center" Content="Add" Click="Add_Click"/>
<Button Grid.Row="7" Grid.Column="2" Margin="3" MinWidth="100" MinHeight="25" HorizontalAlignment="Center" Content="Clear" Click="Clear_Click"/>
</Grid>
Why don't you use data binding?
For each of the text boxes that you have, bind your TextBox.Text to its corresponding property in the view model, something like this:
<TextBox Text={Binding FirstName} />
Then, assign your FirstName, LastName...etc. properties to values and raise INotifyPropertyChanged.PropertyChanged for each of the properties (your view model should implement INotifyPropertyChanged) and your view (i.e. UI) should get updated.
I don't agree with any of the answers posted here. The question doesn't seem to be correct.
If you have a list of Family members. Then how can you show it as a single item. How do you know which item you want to display.
Hence my suggestion is to use a listbox and using data binding, create a view to display the current selected Family member's data in that view.
use foreach loop through list as:
foreach(var a in findFamily)
{
txtbox.text=a[0].tostring();
txtbox2.text=a[1].tostring();
}
or use:
txtbox.text = findFamily.Select(a => a[0].ToString()).FirstOrDefault().ToString();
I'm working on a WIN 8.1 App. In my App I have a ListView where I'm binding a observable collection from a ViewModel. So far everything works fine. The Problem is, that in the Background all the Data will be loaded correctly, but my ListView displays after approximately 40 elements, from the beginning... In the Background the right Object is selected and 80 Objects are loaded.
Could it be a Problem with the Scrolling?
Does anyone know, how to solve this issue?
From an other Page, i navigate to the Page with the ListView:
private void ShowReturnData()
{
ReturnViewModel retVM = new ReturnViewModel(_navigationService, SelectedTour);
_navigationService.NavigateTo(ViewModelLocator.ReturnPageKey, retVM);
}
In my ViewModel Constructor, I add my data to the observable Collection:
I'm working with MVVMlight.
Properties (ObservableCollection, SelectedItem):
--> observable Collection
/// <summary>
/// The <see cref="Data" /> property's name.
/// </summary>
public const string DataPropertyName = "Data";
private ObservableCollection<ReturnData> _myProperty = new ObservableCollection<ReturnData>();
/// <summary>
/// Sets and gets the Data property.
/// Changes to that property's value raise the PropertyChanged event.
/// </summary>
public ObservableCollection<ReturnData> Data
{
get
{
return _myProperty;
}
set
{
if (_myProperty == value)
{
return;
}
_myProperty = value;
RaisePropertyChanged(DataPropertyName);
}
}
--> SelectedItem
/// <summary>
/// The <see cref="SelectedItem" /> property's name.
/// </summary>
public const string SelectedItemPropertyName = "SelectedItem";
private ReturnData _selectedItem = null;
/// <summary>
/// Sets and gets the SelectedTour property.
/// Changes to that property's value raise the PropertyChanged event.
/// </summary>
public ReturnData SelectedItem
{
get
{
return _selectedItem;
}
set
{
if (_selectedItem == value)
{
return;
}
if (_selectedItem != null)
{
_selectedItem.IsFirstItem = false;
_selectedItem.IsLastItem = false;
}
_selectedItem = value;
if (_selectedItem != null)
{
setIsFirstOrLastItem(Data.IndexOf(_selectedItem));
}
RaisePropertyChanged(SelectedItemPropertyName);
}
}
ViewModel Constructor:
public ReturnViewModel(INavigationService navigationService, TourDetailData tourDetails)
{
//Services
_navigationService = navigationService;
//Commands
PrevPageCommand = new RelayCommand(GoToPrevPage);
TourDetails = tourDetails;
TourCustomerName = "Tour " + tourDetails.Tour + " > " + tourDetails.AccountName;
Data = new ObservableCollection<ReturnData>(from i in TourDetails.ReturnData orderby Convert.ToInt32(i.ItemId) select i);
}
XAML:
<ListView x:Name="lvItems"
Grid.Row="2"
SelectedItem="{Binding SelectedItem, Mode=TwoWay}"
ItemTemplate="{StaticResource ReturnDataTemplate}"
ItemContainerStyle="{StaticResource ReturnDataListViewItemStyle}"
ItemsSource="{Binding Data}"
Margin="0,5,0,0"
Loaded="lvItems_Loaded">
</ListView>
DataTemplate:
<DataTemplate x:Key="ReturnDataTemplate">
<Grid x:Name="grid" d:DesignWidth="1344.53" d:DesignHeight="123.228">
<Grid.Resources>
<converter:SelectionConverter x:Key="SelectionConverter" Context="{Binding}" />
</Grid.Resources>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="450*"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<Rectangle Grid.Row="0" Grid.ColumnSpan="5" Height="100" Fill="LightGray" Visibility="Collapsed"/>
<Rectangle Grid.Row="2" Grid.ColumnSpan="5" Height="100" Fill="LightGray" Visibility="Collapsed"/>
<!--<Rectangle Grid.Row="0" Grid.ColumnSpan="5" Height="100" Fill="LightGray" Visibility="{Binding IsFirstItem, Converter={StaticResource BoolToVisibilityConverter}}"/>
<Rectangle Grid.Row="2" Grid.ColumnSpan="5" Height="100" Fill="LightGray" Visibility="{Binding IsLastItem, Converter={StaticResource BoolToVisibilityConverter}}"/>-->
<Rectangle Grid.Row="1" Fill="{StaticResource OrangeHighlight}" Visibility="{Binding IsDirty, Converter={StaticResource BoolToVisibilityConverter}}"/>
<StackPanel Grid.Row="1" Grid.Column="1" VerticalAlignment="Center" Margin="15,0">
<TextBlock TextWrapping="Wrap" FontSize="42.667" FontFamily="Segoe UI" Text="{Binding ItemId}" FontWeight="SemiBold"/>
<TextBlock TextWrapping="Wrap" Text="{Binding ItemName}" FontSize="32" FontFamily="Segoe UI"/>
</StackPanel>
<!--<TextBox x:Name="tbxReturn" Grid.Row="1" TextWrapping="Wrap" Grid.Column="2" FontFamily="Segoe UI" FontSize="42.667" Text="{Binding Return}" HorizontalAlignment="Center" VerticalAlignment="Center" Style="{StaticResource TextBoxStyleValues}" PreventKeyboardDisplayOnProgrammaticFocus="True" DoubleTapped="tbxReturn_DoubleTapped" GotFocus="tbxReturn_GotFocus" />-->
<TextBox x:Name="tbxReturn" Grid.Row="1" TextWrapping="Wrap" Grid.Column="2" FontFamily="Segoe UI" FontSize="42.667" Text="{Binding Return}" HorizontalAlignment="Center" VerticalAlignment="Center" Style="{StaticResource TextBoxStyleValues}" DoubleTapped="tbxReturn_DoubleTapped" GotFocus="tbxReturn_GotFocus" InputScope="CurrencyAmountAndSymbol" Foreground="#FF520164" />
<TextBox x:Name="tbxMold" Grid.Row="1" TextWrapping="Wrap" Text="{Binding Mildew}" Grid.Column="3" FontFamily="Segoe UI" FontSize="42.667" HorizontalAlignment="Center" VerticalAlignment="Center" Style="{StaticResource TextBoxStyleValues}" DoubleTapped="tbxMold_DoubleTapped" Tapped="tbxMold_Tapped" GotFocus="tbxMold_GotFocus" InputScope="CurrencyAmountAndSymbol" Foreground="#FF019E90" />
<TextBox x:Name="tbxCredit" Grid.Row="1" TextWrapping="Wrap" Text="{Binding Credit}" Grid.Column="4" FontFamily="Segoe UI" FontSize="42.667" HorizontalAlignment="Center" VerticalAlignment="Center" Style="{StaticResource TextBoxStyleValues}" DoubleTapped="tbxCredit_DoubleTapped" Tapped="tbxCredit_Tapped" GotFocus="tbxCredit_GotFocus" InputScope="CurrencyAmountAndSymbol" Foreground="#FF005C9C" />
<!--<Button Grid.Row="1" Content="+" HorizontalAlignment="Stretch" VerticalAlignment="Top" Grid.Column="2" Height="100" Margin="0,-100,0,0" FontSize="48" Style="{StaticResource NumUpDownButtonStyle}" Visibility="{Binding ElementName=lvItems, Path=DataContext.SelectedItem, ConverterParameter=Selected, Converter={StaticResource SelectionConverter}}" Command="{Binding DataContext.IncreaseReturnCommand, ElementName=lvItems}" Opacity="0.9"/>
<Button Grid.Row="1" Content="-" HorizontalAlignment="Stretch" VerticalAlignment="Bottom" Grid.Column="2" Margin="0,0,0,-100" Height="100" FontSize="48" Style="{StaticResource NumUpDownButtonStyle}" Visibility="{Binding ElementName=lvItems, Path=DataContext.SelectedItem, ConverterParameter=Selected, Converter={StaticResource SelectionConverter}}" Command="{Binding DataContext.DecreaseReturnCommand, ElementName=lvItems}" Opacity="0.9"/>
<Button Grid.Row="1" Content="+" HorizontalAlignment="Stretch" VerticalAlignment="Top" Grid.Column="3" Height="100" Margin="0,-100,0,0" FontSize="48" Style="{StaticResource NumUpDownButtonStyle}" Visibility="{Binding ElementName=lvItems, Path=DataContext.SelectedItem, ConverterParameter=Selected, Converter={StaticResource SelectionConverter}}" Command="{Binding DataContext.IncreaseMildewCommand, ElementName=lvItems}" Opacity="0.9"/>
<Button Grid.Row="1" Content="-" HorizontalAlignment="Stretch" VerticalAlignment="Bottom" Grid.Column="3" Margin="0,0,0,-100" Height="100" FontSize="48" Style="{StaticResource NumUpDownButtonStyle}" Visibility="{Binding ElementName=lvItems, Path=DataContext.SelectedItem, ConverterParameter=Selected, Converter={StaticResource SelectionConverter}}" Command="{Binding DataContext.DecreaseMildewCommand, ElementName=lvItems}" Opacity="0.9"/>
<Button Grid.Row="1" Content="+" HorizontalAlignment="Stretch" VerticalAlignment="Top" Grid.Column="4" Height="100" Margin="0,-100,0,0" FontSize="48" Style="{StaticResource NumUpDownButtonStyle}" Visibility="{Binding ElementName=lvItems, Path=DataContext.SelectedItem, ConverterParameter=Selected, Converter={StaticResource SelectionConverter}}" Command="{Binding DataContext.IncreaseCreditCommand, ElementName=lvItems}" Opacity="0.9"/>
<Button Grid.Row="1" Content="-" HorizontalAlignment="Stretch" VerticalAlignment="Bottom" Grid.Column="4" Margin="0,0,0,-100" Height="100" FontSize="48" Style="{StaticResource NumUpDownButtonStyle}" Visibility="{Binding ElementName=lvItems, Path=DataContext.SelectedItem, ConverterParameter=Selected, Converter={StaticResource SelectionConverter}}" Command="{Binding DataContext.DecreaseCreditCommand, ElementName=lvItems}" Opacity="0.9"/>-->
</Grid>
</DataTemplate>
Style:
<Style x:Key="ReturnDataListViewItemStyle" TargetType="ListViewItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListViewItem">
<ListViewItemPresenter x:Name="listViewItemPresenter" d:DesignWidth="938.908" d:DesignHeight="103.083"
ContentMargin="0"
DragOpacity="{ThemeResource ListViewItemDragThemeOpacity}"
DisabledOpacity="{ThemeResource ListViewItemDisabledThemeOpacity}"
HorizontalContentAlignment="Stretch"
Padding="0"
PointerOverBackgroundMargin="1"
ReorderHintOffset="{ThemeResource ListViewItemReorderHintThemeOffset}"
SelectionCheckMarkVisualEnabled="False"
SelectedBorderThickness="0"
VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"
Margin="15,0,0,0"
SelectedForeground="Black"
SelectedPointerOverBackground="{StaticResource OrangeBackground}"
SelectedPointerOverBorderBrush="{StaticResource OrangeBackground}"
SelectedBackground="{StaticResource OrangeBackground}"
DataContext="{Binding SelectedItem}"
Content="{Binding Mode=OneWay}"
ContentTransitions="{TemplateBinding ContentTransitions}"
PlaceholderBackground="{StaticResource BackgroundGray}">
</ListViewItemPresenter>
</ControlTemplate>
</Setter.Value>
</Setter>
<!--<Setter Property="ContentTemplate" Value="{StaticResource ReturnDataTemplate}"/>-->
</Style>
In the Code behind of the XAML Page, I added the behavior of the ScrollViewer:
private void lvItems_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
SetScrollViewer();
}
private async void SetScrollViewer()
{
if (lvItems.SelectedItem == null)
return;
var item = lvItems.SelectedItem;
var listViewItem = (FrameworkElement)lvItems.ContainerFromItem(item);
if (listViewItem == null)
{
lvItems.ScrollIntoView(item);
}
while (listViewItem == null)
{
await Task.Delay(1);
listViewItem = (FrameworkElement)lvItems.ContainerFromItem(item);
}
var topLeft =
listViewItem
.TransformToVisual(lvItems)
.TransformPoint(new Point()).Y;
var lvih = listViewItem.ActualHeight;
var lvh = lvItems.ActualHeight;
var desiredTopLeft = (lvh - lvih) / 2.0;
var desiredDelta = topLeft - desiredTopLeft;
// Calculations relative to the ScrollViewer within the ListView
var scrollViewer = lvItems.GetFirstDescendantOfType<ScrollViewer>();
var currentOffset = scrollViewer.VerticalOffset;
var desiredOffset = currentOffset + desiredDelta;
//scrollViewer.ScrollToVerticalOffset(desiredOffset);
// better yet if building for Windows 8.1 to make the scrolling smoother use:
scrollViewer.ChangeView(null, desiredOffset, null);
}
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;
}
}
}