I am just new to WPF, Caliburn.Micro and Dapper. I have three combo boxes: the first one is for the region, the second one is for the provinces in the particular selected region and the third one are the cities in the particular selected province. What I want to achieve is that when I selected a particular region it will display all the provinces in that region, the same with the province combo box, when selected it will display all the cities associated with that province. Can this be done in a single method? Here is my code so far.
DataAccess
public List<RegionModel> GetRegion_All()
{
List<RegionModel> output;
using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(GlobalConfig.CnnString(db)))
{
output = connection.Query<RegionModel>("dbo.spRegion_GetAll").ToList();
var p = new DynamicParameters();
foreach (RegionModel region in output)
{
p = new DynamicParameters();
p.Add("#RegionId", region.Id);
region.Provinces = connection.Query<ProvinceModel>("dbo.spProvince_ByRegion", p, commandType: CommandType.StoredProcedure).ToList();
foreach (ProvinceModel province in region.Provinces)
{
p = new DynamicParameters();
p.Add("#ProvinceId", province.Id);
region.Cities = connection.Query<CityModel>("dbo.spCity_ByProvince", p, commandType: CommandType.StoredProcedure).ToList();
}
}
}
return output;
}
Models
public class RegionModel
{
public int Id { get; set; }
public string Region { get; set; }
public string RegionName { get; set; }
public List<ProvinceModel> Provinces { get; set; } = new List<ProvinceModel>();
public List<CityModel> Cities { get; set; } = new List<CityModel>();
public List<BarangayModel> Barangays { get; set; } = new List<BarangayModel>();
}
public class ProvinceModel
{
public int Id { get; set; }
public string Province { get; set; }
public int RegionId { get; set; }
}
public class CityModel
{
public int Id { get; set; }
public string City { get; set; }
public int ProvinceId { get; set; }
public int ZipCode { get; set; }
}
ViewModel
public class ShellViewModel : Screen
{
private BindableCollection<RegionModel> _region;
private RegionModel _selectedRegion;
private ProvinceModel _selectedProvince;
public ShellViewModel()
{
GlobalConfig.InitializeConnections(DatabaseType.Sql);
Region = new BindableCollection<RegionModel>(GlobalConfig.Connection.GetRegion_All());
}
public BindableCollection<RegionModel> Region
{
get { return _region; }
set
{
_region = value;
}
}
public RegionModel SelectedRegion
{
get { return _selectedRegion; }
set
{
_selectedRegion = value;
NotifyOfPropertyChange(() => SelectedRegion);
}
}
public ProvinceModel SelectedProvince
{
get { return _selectedProvince; }
set
{
_selectedProvince = value;
NotifyOfPropertyChange(() => SelectedRegion);
}
}
View
<Window x:Class="WPFUI.Views.ShellView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WPFUI.Views"
mc:Ignorable="d" WindowStartupLocation="CenterScreen"
Title="ShellView" Height="450" Width="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<ComboBox Grid.Row="0" x:Name="Region" >
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding RegionName}" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<ComboBox Grid.Row="1" x:Name="SelectedRegion_Provinces" >
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Province}" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<ComboBox Grid.Row="2" x:Name="SelectedRegion_Cities" >
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding City}" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
Most of my codes ideas are from the tutorials I found in youtube, since references and materials for WPF, Caliburn.Micro and Dapper are very hard to find. Please be patient with my code :)
You have lot of mistake and you dont use the power of Caliburn
The wpf definition:
with Caliburn if you give name Region for combobox, it waits a bindableCollection with same name (Region) and SelectedItem is named SelectedRegion
(see name convention with Caliburn). So i choose Region, Province & City
In the different models i have renamed all strings RegionName, ProvinceName and CityName.
<ComboBox Grid.Row="0" x:Name="Region" >
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding RegionName}" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<ComboBox Grid.Row="1" x:Name="Province" >
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding ProvinceName}" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<ComboBox Grid.Row="2" x:Name="City" >
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding CityName}" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
then, i have modified your class definition:
public class RegionModel:PropertyChangedBase
{
public int Id { get; set; }
public string Region { get; set; }
public string RegionName { get; set; }
// each Region has its Provinces
public List<ProvinceModel> Provinces { get; set; } = new List<ProvinceModel>();
}
public class ProvinceModel:PropertyChangedBase
{
public int Id { get; set; }
public string ProvinceName { get; set; }
public int RegionId { get; set; }
// each Province has its Cities
public List<CityModel> Cities { get; set; } = new List<CityModel>();
}
public class CityModel:PropertyChangedBase
{
public int Id { get; set; }
public string CityName { get; set; }
public int ProvinceId { get; set; }
public int ZipCode { get; set; }
}
Then in ViewModel i add the different BindableCollection Region, Province & City dont forget to add
using Caliburn.Micro;
in the using definion. Then Add the Selected Definition
public class ShellViewModel : Screen
{
private RegionModel selectedRegion;
private ProvinceModel selectedProvince;
private CityModel selectedCity;
private BindableCollection<RegionModel> _region;
private BindableCollection<ProvinceModel> _province;
private BindableCollection<CityModel> _city;
public BindableCollection<RegionModel> Region
{
get { return _region; }
set
{
_region = value;
NotifyOfPropertyChange(() => Region);
}
}
public BindableCollection<ProvinceModel> Province
{
get { return _province; }
set
{
_province = value;
NotifyOfPropertyChange(() => Province);
}
}
public BindableCollection<CityModel> City
{
get { return _city; }
set
{
_city = value;
NotifyOfPropertyChange(() => City);
}
}
public RegionModel SelectedRegion
{
get { return selectedRegion; }
set
{
selectedRegion = value;
NotifyOfPropertyChange(() => SelectedRegion);
Province.Clear();
Province.AddRange(selectedRegion.Provinces);
NotifyOfPropertyChange(() => Province);
}
}
public ProvinceModel SelectedProvince
{
get { return selectedProvince; }
set
{
selectedProvince = value;
NotifyOfPropertyChange(() => SelectedProvince);
City.Clear();
City.AddRange(selectedProvince.Cities);
NotifyOfPropertyChange(() => City);
}
}
public CityModel SelectedCity
{
get { return selectedCity; }
set
{
selectedCity = value;
NotifyOfPropertyChange(() => SelectedCity);
}
}
public ShellViewModel()
{
// to DO INITIALIZE Regions
//
Province = new BindableCollection<ProvinceModel>();
City = new BindableCollection<CityModel>();
Region = new BindableCollection<RegionModel>(Regions);
}
and you have a functional sample
Each time you select a region, the associated provinces are loaded and same thing if you select a province for the associated Cities
Related
I have a hierarchical list of objects whose children are objects of a different type. The classes for them are described as follows:
public class Production
{
public string name { get; set; }
public string id { get; set; }
public List<Plant> plants { get; set; }
}
public class Plant
{
public string name { get; set; }
public string id { get; set; }
public List<Scheme> schemes { get; set; }
}
public class Scheme
{
public string name { get; set; }
public string id { get; set; }
}
And the main class which contains a list of productions and methods for filling the main menu:
public class DocumentProviderMenu
{
public List<Production> productions { get; set; }
public DocumentProviderMenu()
{
ExecuteUpdateMenu();
}
private void ExecuteUpdateMenu() {/*Uploding menu method}
Finally, the TreeView xaml:
<TreeView ItemsSource="{Binding Menu.productions}">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type mod:Production}"
ItemsSource="{Binding plants}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding name}"/>
</StackPanel>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type mod:Plant}"
ItemsSource="{Binding schemes}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding name}"/>
</StackPanel>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type mod:Scheme}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding name}"/>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
Where Menu is a property of ViewModel.So I declared the fields in ViewModel like:
public Production SelectedProduction
{
get => _SelectedProduction;
set
{
_SelectedProduction = value;
OnPropertyChanged(nameof(SelectedProduction));
}
}
private Production _SelectedProduction;
for 3 types - Production,Plant,Scheme.I can bind the selected item but only to one type (this question helped me Data binding to SelectedItem in a WPF Treeview). Is there a way to bind 3 of my types to the selected item?
These elements must have something in common, e.g. an interface:
XAML:
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1" Width="640" Height="480"
mc:Ignorable="d" d:DataContext="{d:DesignInstance local:Model}">
<Window.DataContext>
<local:Model />
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Text="{Binding SelectedProduction, StringFormat='{}Selected item: {0}' }" />
<TreeView ItemsSource="{Binding Productions}" SelectedItemChanged="TreeView_OnSelectedItemChanged" Grid.Row="1">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type local:Production}"
ItemsSource="{Binding Plants}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" />
</StackPanel>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:Plant}"
ItemsSource="{Binding Schemes}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" />
</StackPanel>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:Scheme}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" />
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
</Grid>
</Window>
Code:
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
namespace WpfApp1;
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
}
private void TreeView_OnSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
(DataContext as Model)!.SelectedProduction = e.NewValue as ITreeElement;
}
}
internal class Model : INotifyPropertyChanged
{
private ITreeElement? _selectedProduction;
public Model()
{
Productions = new List<ITreeElement>
{
new Production
{
Name = "production",
Plants = new List<Plant>
{
new()
{
Name = "plant 1",
Schemes = new List<Scheme>
{
new()
{
Name = "scheme 1"
},
new()
{
Name = "scheme 2"
}
}
},
new()
{
Name = "plant 2",
Schemes = new List<Scheme>
{
new()
{
Name = "scheme 3"
},
new()
{
Name = "scheme 4"
}
}
}
}
}
};
}
public List<ITreeElement> Productions { get; }
public ITreeElement? SelectedProduction
{
get => _selectedProduction;
set => SetField(ref _selectedProduction, value);
}
public event PropertyChangedEventHandler? PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected bool SetField<T>(ref T field, T value, [CallerMemberName] string? propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
field = value;
OnPropertyChanged(propertyName);
return true;
}
}
public interface ITreeElement
{
string Name { get; set; }
string Id { get; set; }
}
public class Production : ITreeElement
{
public List<Plant> Plants { get; set; }
public string Name { get; set; }
public string Id { get; set; }
}
public class Plant : ITreeElement
{
public List<Scheme> Schemes { get; set; }
public string Name { get; set; }
public string Id { get; set; }
}
public class Scheme : ITreeElement
{
public string Name { get; set; }
public string Id { get; set; }
}
I am creating an application with an MVVM model, in one of my views I have an ObservableCollection where by means of a button I create a new element and it appears on the screen, the problem is that I have a button to update that changes the name of the ListViewItem , and this name doesn't change until I switch between views
Problem
The DNP3-Master are my Items and the button I activate changes the name to "Test" but it is not updated until I change my view (this is a UserControl)
MasterViwModel
class MasterViewModel : ObservableObject
{
public ushort count { get; set; }
public ObservableCollection<MasterTraceModel> MasterReference { get; set; }
public RelayCommand CreateMaster { get; set; }
public RelayCommand Update { get; set; }
private ObservableCollection<MasterModel> _masterList;
public ObservableCollection<MasterModel> MasterList
{
get { return _masterList; }
set { _masterList = value; OnPropertyChanged(); }
}
private MasterModel _selectedMaster;//SelectedItem from ListView
public MasterModel SelectedMaster
{
get { return _selectedMaster; }
set { _selectedMaster = value; OnPropertyChanged(); }
}
public MasterViewModel()
{
MasterList = new ObservableCollection<MasterModel>();//my Observable Collections
//Stuff
this.count = 1;
//Stuff
CreateMaster = new RelayCommand(o =>
{
MasterList.Add(new MasterModel(this.count, "127.0.0.1", "20000", runtime));
this.count = (ushort)(count + 1);
});//Here I add the elements to my ObservableCollections
//Stuff
Update = new RelayCommand(o =>
{
SelectedMaster.SetName("Test");
});
}
}
MasterView
<UserControl x:Class="Prototype.MVVM.View.MasterView"
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:viewmodel="clr-namespace:Prototype.MVVM.ViewModel"
d:DataContext="{d:DesignInstance Type=viewmodel:MasterViewModel}"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
<Border Margin="20,20,0,20" Background="#151515" CornerRadius="8">
<ListView Name="MasterListView" Margin="5"
ItemsSource="{Binding MasterList}"
SelectedItem="{Binding SelectedMaster}"
ItemContainerStyle="{StaticResource MasterTheme}"
Background="Transparent"
BorderThickness="0"
/>
</Border>
<StackPanel Grid.Column="1" Margin="0,20,0,0">
<Button Margin="0,0,0,10" Grid.Column="1" Style="{StaticResource SmallBtn}" Command="{Binding Update}">
<Image Height="24" Width="24" Source="/Icons/cil-reload.png" RenderOptions.BitmapScalingMode="NearestNeighbor"/>
</Button>
</StackPanel>
</Grid>
</UserControl>
MasterModel
class MasterModel : ObservableObject
{
public string Name { get; set; }
public ushort Adress { get; set; }
public string Host { get; set; }
public string Port { get; set; }
public Runtime _runtime { get; set; }
public MasterChannel channel { get; set; }
public ConnectStrategy CStrategy { get; set; }
public string[] Delay { get; set; }
public MasterModel(ushort Adress, string Host, string Port, Runtime runtime)
{
this.Name = "DNP3-Master-" + Adress.ToString();
this.Adress = Adress;
this.Host = Host;
this.Port = Port;
this._runtime = runtime;
CStrategy = new ConnectStrategy();
//CStrategy.MinConnectDelay = new TimeSp
Delay = new string[3];
Delay[0] = CStrategy.MinConnectDelay.ToString();
Delay[1] = CStrategy.MaxConnectDelay.ToString();
Delay[2] = CStrategy.ReconnectDelay.ToString();
this.channel = MasterChannel.CreateTcpChannel(//Stuff);
}
public void SetName(string name)
{
this.Name = name;
}
public void Star(Runtime runtime)
{
Task.Run(async () =>
{
try
{
await MasterFunctions.RunChannel(channel);
}
finally
{
runtime.Shutdown();
}
});
}
The MasterModel class should implement the INotifyPropertyChanged event and raise the PropertyChanged event for the data-bound property when you call SetName:
private string _name;
public string Name
{
get { return _name; }
set { _name = value; OnPropertyChanged(); }
}
Using an ObservableCollection<T> doesn't replace the need to implement INotifyPropertyChanged and raise change notifications for the individual items in the collection. It notifies the view when items are added to and removed from the collection only.
I just began working with the MVVM layout and I cannot seem to display anything in my collectionView List. I believe it's my binding, unfortunately I don't really understand how I am supposed to bind a grouped list + the ViewModel. I read to bind to the path no the source, but I'm pretty sure I am doing this incorrectly. I have checked to see if I am even getting shares to load and I am, they're just not displaying.
Model -- Share
[JsonProperty("iSpottedID")]
public int ID { get; set; }
[JsonProperty("sShoppingList")]
[MaxLength(255)]
public string ShoppingName { get; set; }
[JsonProperty("dtInfoUpdate")]
[MaxLength(20)]
public string CreateDate { get; set; }
[JsonProperty("iProductID")]
public int ProductID { get; set; }
[Indexed]
[JsonProperty("sLocation")]
[MaxLength(255)]
public string LocationName { get; set; }
[JsonProperty("tvCardJson")]
public string JsonString { get; set; }
ViewModel -- SharesViewModel
public class SharesViewModel : BaseViewModel
{
#region Properties
private int _id;
public int ID
{
get { return _id; }
set
{
SetValue(ref _id, value);
OnPropertyChanged(nameof(ID));
}
}
private string _longName;
public string LongName
{
get { return _longName; }
set
{
SetValue(ref _longName, value);
OnPropertyChanged(nameof(LongName));
}
}
private string _date;
public string CreateDate
{
get{ return _date;}
set
{
SetValue(ref _date, value);
OnPropertyChanged(nameof(CreateDate));
}
}
private int _prodID;
public int ProductID
{
get { return _id; }
set
{
SetValue(ref _prodID, value);
OnPropertyChanged(nameof(ProductID));
}
}
private string _json;
public string JsonString
{
get { return _json; }
set
{
SetValue(ref _json, value);
OnPropertyChanged(nameof(JsonString));
}
}
private string _location;
public string LocationName
{
get { return _location; }
set
{
SetValue(ref _location, value);
OnPropertyChanged(nameof(LocationName));
}
}
//ADD-ONS
public string Address
{
get
{
if (!string.IsNullOrEmpty(JsonString))
{
var jsonDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(JsonString);
if (jsonDict.ContainsKey("address"))
if (jsonDict["address"] != "")
return jsonDict["address"];
}
return null;
}
}
private ImageSource _imageLink;
public ImageSource ImageLink
{
get
{
if(ProductID != 0)
{
...
return ImageSource.FromUri(link);
}
return null;
}
}
#endregion
public SharesViewModel(){}
public SharesViewModel(Share share)
{
ID = share.ID;
ProductID = share.ProductID;
JsonString = share.JsonString;
CreateDate = share.CreateDate;
LocationName = share.LocationName;
}
List View Model -- SharesListViewlModel
public class SharesListViewModel : BaseViewModel
{
private SharesViewModel _selectedShare;
private bool _isDataLoaded;
//grouped list
public ObservableCollection<LocationSpotGroups<string, SharesViewModel>> Shares { get; set; }
...
public ICommand OpenMoreSharesCommand { get; private set; }
public ICommand LoadDataCommand { get; private set; }
public SharesListViewModel(Position NW , Position SE)
{
_nw = NW;
_se = SE;
LoadDataCommand = new Command(async () => await LoadData());
OpenMoreSharesCommand = new Command<SharesViewModel>(async (share) => await OpenMoreShares(share));
public ObservableCollection<SharesViewModel> sList { get; set; }
= new ObservableCollection<SharesViewModel>();
}
private async Task LoadData()
{
if (_isDataLoaded)
return;
var list = await _connection.GetAllRegionShares(_nw, _se);
foreach (var spot in list)
{
sList.Add(new SharesViewModel(spot));
}
var sorted = from item in sList
orderby item.LocationName
group item by item.LocationName into itemGroup
select new LocationSpotGroups<string, SharesViewModel>(itemGroup.Key, itemGroup);
Shares = new ObservableCollection<LocationSpotGroups<string, SharesViewModel>>(sorted);
}
LocationSpotGroups
public class LocationSpotGroups<K, T> : ObservableCollection<T>
{
public K GroupKey { get; set; }
public IEnumerable<T> GroupedItem { get; set; }
public LocationSpotGroups(K key, IEnumerable<T> shares)
{
GroupKey = key;
GroupedItem = shares;
foreach (var item in shares)
{
this.Items.Add(item);
}
}
}
SharesPage XAML
<CollectionView x:Name="CollectionList"
VerticalOptions="FillAndExpand"
ItemsSource="{Binding Shares}"
IsGrouped="True">
<!--HEADER-->
<CollectionView.GroupHeaderTemplate>
<DataTemplate>
<StackLayout Orientation="Horizontal"
Padding="5"
BackgroundColor="#f7f7fb">
<Label x:Name="labelname"
Text="{Binding GroupKey}"
HorizontalOptions="Start"
VerticalOptions="Center"
TextColor="gray" />
</StackLayout>
</DataTemplate>
</CollectionView.GroupHeaderTemplate>
<CollectionView.ItemsLayout>
<GridItemsLayout Orientation="Vertical" Span="2" />
</CollectionView.ItemsLayout>
<!--BODY-->
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid Padding="5" Margin="8">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="50" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ImageButton Source="{Binding ImageLink}"
WidthRequest="150"
HeightRequest="150"
Grid.ColumnSpan="2"
CornerRadius="15"
Aspect="AspectFill"
Grid.Row="0"
Grid.Column="0"/>
<Label Text="{Binding ShoppingName}"
Grid.Row="1"
Grid.Column="0"/>
<Label Text="More"
Grid.Row="1"
Grid.Column="1"
HorizontalTextAlignment="End"/>
<Label Text="{Binding CreateDate}"
Grid.Row="2"
Grid.Column="0"/>
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
SharesPage CS
public SharesPage( Position NW, Position SE )
{
InitializeComponent();
ViewModel = new SharesListViewModel(NW, SE);
}
public SharesListViewModel ViewModel
{
get { return BindingContext as SharesListViewModel; }
set { BindingContext = value; }
}
protected override void OnAppearing()
{
ViewModel.LoadDataCommand.Execute(null);
base.OnAppearing();
}
Loading the data in the constructor works if the data is not a lot, which is wasn't in my case. Everything loads perfectly.
I need to get all selected radio button tags and group name after user clicks on Appbar button submit and store it in a List.
So i can compare the user submitted answer list with the list from the server..
If i use Checked="Answer_Checked" , List is over written when i click another radio button in Question 2
public class RootObject
{
public RootObject(int id, string question, int qno, int qcount)
{
this.id = id;
this.question = question;
this.qcount = qcount;
this.qno = qno;
}
public int id { get; set; }
public string question { get; set; }
public int qcount { get; set; }
public int qno { get; set; }
public int time { get; set; }
}
public class AnswerObject
{
public AnswerObject(int question_id, int answer_id, string answer, int is_right_option)
{
this.question_id = question_id;
this.answer_id = answer_id;
this.answer = answer;
this.is_right_option = is_right_option;
}
public int question_id { get; set; }
public int answer_id { get; set; }
public string answer { get; set; }
public int is_right_option { get; set; }
}
public class Question
{
public string QuestionName { get; set; }
public int qcount { get; set; }
public int qno { get; set; }
public ObservableCollection<Option> options { get; set; }
}
public class Option
{
public string QuestionAnswer { get; set; }
public string groupname { get; set; }
public int IsCorrect { get; set; }
}
C# Coding
var result1 = await response1.Content.ReadAsStringAsync();
var objResponse1 = JsonConvert.DeserializeObject<List<RootObject>>(result1);
var result2 = await response2.Content.ReadAsStringAsync();
var objResponse2 = JsonConvert.DeserializeObject<List<AnswerObject>>(result2);
for (int i = 0; i < objResponse1.LongCount(); i++)
{
ObservableCollection<Option> options1 = new ObservableCollection<Option>();
for (int j = 0; j < objResponse2.LongCount(); j++)
{
if (objResponse1[i].id == objResponse2[j].question_id)
{
options1.Add(new Option() { QuestionAnswer = objResponse2[j].answer, IsCorrect = objResponse2[j].is_right_option, groupname = objResponse2[j].question_id.ToString() });
}
}
questions.Add(new Question() { QuestionName = objResponse1[i].question, qno=i + 1, qcount =objResponse1.Count, options = options1 });
}
flipView.ItemsSource = questions;
XAML Coding
<FlipView x:Name="flipView" HorizontalAlignment="Left" VerticalAlignment="Top" ItemsSource="{Binding}" Margin="0,35,0,0">
<FlipView.ItemTemplate>
<DataTemplate>
<ListView Name="ItemData" SelectionMode="None" ItemsSource="{Binding}" >
<Grid x:Name="ContentPanel">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock x:Name="Testing" Margin="10,20" FontSize="22.333">
<Run Text="{Binding qno}"/>
<Run Text="of"/>
<Run Text="{Binding qcount}"/>
</TextBlock>
<TextBlock x:Name="Question" Text="{Binding QuestionName}" Margin="10,60" VerticalAlignment="Top" HorizontalAlignment="Left" FontSize="22.333" TextWrapping="Wrap"/>
<ListBox Grid.Row="1" Padding="0" Margin="10,-10" ItemsSource="{Binding options}" Background="Transparent">
<ListBox.ItemTemplate>
<DataTemplate>
<RadioButton x:Name="Answer" GroupName="{Binding groupname}" Checked="Answer_Checked" Tag="{Binding IsCorrect}" Margin="10,2">
<RadioButton.Content>
<TextBlock Text="{Binding QuestionAnswer}" Foreground="White"/>
</RadioButton.Content>
</RadioButton>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</ListView>
</DataTemplate>
</FlipView.ItemTemplate>
</FlipView>
Answer in JSON Format
[{"question_id":3,"answer_id":1,"answer":"10%","is_right_option":0},{"question_id":3,"answer_id":2,"answer":"10.25%","is_right_option":1},{"question_id":3,"answer_id":3,"answer":"10.5%","is_right_option":0},{"question_id":3,"answer_id":4,"answer":"None of these","is_right_option":0},{"question_id":4,"answer_id":5,"answer":"Rs. 2.04","is_right_option":1},{"question_id":4,"answer_id":6,"answer":"Rs. 3.06","is_right_option":0},{"question_id":4,"answer_id":7,"answer":"Rs. 4.80","is_right_option":0},{"question_id":4,"answer_id":8,"answer":"Rs. 8.30","is_right_option":0}]
Question in JSON Format
[{"id":3,"question":"An automobile financier claims to be lending money at simple interest, but he includes the interest every six months for calculating the principal. If he is charging an interest of 10%, the effective rate of interest becomes: ","time":1},{"id":4,"question":"What is the difference between the compound interests on Rs. 5000 for 1 years at 4% per annum compounded yearly and half-yearly? ","time":1}]
I solved it using Dictionary instead of using List
private void Answer_Checked(object sender, RoutedEventArgs e) // Radio button click
{
var radio = sender as RadioButton;
bool check = Convert.ToBoolean(radio.IsChecked);
if(check)
{
Answer[Convert.ToInt16(radio.GroupName)] = Convert.ToInt16(radio.Tag);
}
}
public async void Check_Result() // Evaluate result
{
foreach (KeyValuePair<int, int> count in Answer)
{
if (count.Value == 1)
{
result++;
}
}
MessageDialog showresult = new MessageDialog(result.ToString());
await showresult.ShowAsync();
Frame.Navigate(typeof(MainPage), null);
}
public void TestSubmit_Click(object sender, RoutedEventArgs e) // AppBar button click
{
Check_Result();
}
I am currently implementing the application that displays hierarchy using ListBoxes (please do not suggest using TreeView, ListBoxes are needed).
It looks like that in the article: WPF’s CollectionViewSource (with source code).
Classes:
public class Mountains : ObservableCollection<Mountain>
{
public ObservableCollection<Lift> Lifts { get; }
public string Name { get; }
}
public class Lift
{
public ObservableCollection<string> Runs { get; }
}
The example uses CollectionViewSource instances (see XAML) to simplify the design.
An instance of Mountains class is the DataContext for the window.
The problem is: I would like that the Mountains class to have SelectedRun property and it should be set to currently selected run.
public class Mountains : ObservableCollection<Mountain>
{
public ObservableCollection<Lift> Lifts { get; }
public string Name { get; }
public string SelectedRun { get; set; }
}
Maybe I've missed something basic principle, but how can I achieve this?
You may want to read about the use of '/' in bindings. See the section 'current item pointers' on this MSDN article.
Here's my solution:
Xaml
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Margin="5" Grid.Row="0" Grid.Column="0" Text="Mountains"/>
<TextBlock Margin="5" Grid.Row="0" Grid.Column="1" Text="Lifts"/>
<TextBlock Margin="5" Grid.Row="0" Grid.Column="2" Text="Runs"/>
<ListBox Grid.Row="1" Grid.Column="0" Margin="5"
ItemsSource="{Binding Mountains}" DisplayMemberPath="Name"
IsSynchronizedWithCurrentItem="True" />
<ListBox Grid.Row="1" Grid.Column="1" Margin="5"
ItemsSource="{Binding Mountains/Lifts}" DisplayMemberPath="Name"
IsSynchronizedWithCurrentItem="True"/>
<ListBox Grid.Row="1" Grid.Column="2" Margin="5"
ItemsSource="{Binding Mountains/Lifts/Runs}"
IsSynchronizedWithCurrentItem="True"
SelectedItem="{Binding SelectedRun}"/>
</Grid>
C# (note, you don't need to implement INotifyPropertyChanged unless the properties will be changed and not just selected)
public class MountainsViewModel
{
public MountainsViewModel()
{
Mountains = new ObservableCollection<Mountain>
{
new Mountain
{
Name = "Whistler",
Lifts = new ObservableCollection<Lift>
{
new Lift
{
Name = "Big Red",
Runs = new ObservableCollection<string>
{
"Headwall",
"Fisheye",
"Jimmy's"
}
},
new Lift
{
Name = "Garbanzo",
Runs = new ObservableCollection<string>
{
"Headwall1",
"Fisheye1",
"Jimmy's1"
}
},
new Lift {Name = "Orange"},
}
},
new Mountain
{
Name = "Stevens",
Lifts = new ObservableCollection<Lift>
{
new Lift {Name = "One"},
new Lift {Name = "Two"},
new Lift {Name = "Three"},
}
},
new Mountain {Name = "Crystal"},
};
}
public string Name { get; set; }
private string _selectedRun;
public string SelectedRun
{
get { return _selectedRun; }
set
{
Debug.WriteLine(value);
_selectedRun = value;
}
}
public ObservableCollection<Mountain> Mountains { get; set; }
}
public class Mountain
{
public string Name { get; set; }
public ObservableCollection<Lift> Lifts { get; set; }
}
public class Lift
{
public string Name { get; set; }
public ObservableCollection<string> Runs { get; set; }
}
Here's how I would do it. You want to make sure that you fire the INotifyPropertyChanged event when setting the properties. To get the Selected Run you'll have to get MainViewModel.SelectedMountain.SelectedLift.SelectedRun.
public class MainViewModel: ViewModelBae
{
ObservableCollection<MountainViewModel> mountains
public ObservableCollection<MountainViewModel> Mountains
{
get { return mountains; }
set
{
if (mountains != value)
{
mountains = value;
RaisePropertyChanged("Mountains");
}
}
}
MountainViewModel selectedMountain
public MountainViewModel SelectedMountain
{
get { return selectedMountain; }
set
{
if (selectedMountain != value)
{
selectedMountain = value;
RaisePropertyChanged("SelectedMountain");
}
}
}
}
public class MountainViewModel: ViewModelBae
{
ObservableCollection<LiftViewModel> lifts
public ObservableCollection<LiftViewModel> Lifts
{
get { return lifts; }
set
{
if (lifts != value)
{
lifts = value;
RaisePropertyChanged("Lifts");
}
}
}
LiftViewModel selectedLift
public LiftViewModel SelectedLift
{
get { return selectedLift; }
set
{
if (selectedLift != value)
{
selectedLift = value;
RaisePropertyChanged("SelectedLift");
}
}
}
}
public class LiftViewModel: ViewModelBae
{
ObservableCollection<string> runs
public ObservableCollection<string> Runs
{
get { return runs; }
set
{
if (runs != value)
{
runs = value;
RaisePropertyChanged("Runs");
}
}
}
string selectedRun
public string SelectedRun
{
get { return selectedLift; }
set
{
if (selectedLift != value)
{
selectedLift = value;
RaisePropertyChanged("SelectedLift");
}
}
}
}
<ListBox ItemsSource="{Binding Mountains}" SelectedItem="{Binding SelectedMountain, Mode=TwoWay}">
<ListBox ItemsSource="{Binding SelectedMountain.Lifts}" SelectedItem="{Binding SelectedMountain.SelectedLift, Mode=TwoWay}">
<ListBox ItemsSource="{Binding SelectedMountain.SelectedLift.Runs}" SelectedItem="{Binding SelectedMountain.SelectedLift.SelectedRun, Mode=TwoWay}">
Your ViewModel should not also be a collection, it should contain collections and properties which are bound to the view. SelectedRun should be a property of this ViewModel (MountainViewModel) not Mountains. MountainViewModel should expose the Mountains collection and SelectedRun and should be bound to the listboxes' ItemsSource and SelectedItem.