I'm having a problem with a ListView for Windows Phone:
I'm using a databinding to display all items in a folder, but when I try to iterate through them, I don't get a control, but the class I use to get the items in the LocalFolder of the app (The subjectpicker class)!
SubjectPicker class:
class SubjectPicker {
public static async Task<List<SubjectPicker>> SubjectData() {
List<string> Names = new List<string>();
List<Brush> Colors = new List<Brush>();
List<string> Items = new List<string>();
List<List<TestOrTask>> TestsAndTasks = new List<List<TestOrTask>>();
StorageFolder LocalFolder = ApplicationData.Current.LocalFolder;
var files = await LocalFolder.GetFilesAsync();
foreach (var file in files) {
//await file.DeleteAsync();
List<TestOrTask> TAT = new List<TestOrTask>();
Names.Add(file.DisplayName);
bool readItems = false;
var contents = await FileIO.ReadLinesAsync(file);
foreach (var content in contents) {
if (content.Contains("Subject Color")) {
string colorname = content.Replace("Subject Color: ", "");
Colors.Add(ColorConverter.fromString_Brush(colorname));
}
else if (content == "<Items>") readItems = true;
else if (content == "</Items>") readItems = false;
if (readItems == true && content != "") {
// Layout: <Name>: <Score>/<Maximum>|<YYYY>/<MM>/<DD>
string name = content.Split(':')[0];
string Score = content.Split(':')[1].Replace(" ", "");
string Date = content.Split('|')[1];
TestOrTask TOT = new TestOrTask(
name,
double.Parse(Score.Split('/')[0]),
double.Parse(Score.Split('/')[1]),
new DateTime(
Int32.Parse(Date.Split('/')[0]),
Int32.Parse(Date.Split('/')[1]),
Int32.Parse(Date.Split('/')[2])));
TAT.Add(TOT);
}
}
Items.Add("Aantal Testen & Taken: " + TAT.Count.ToString());
TestsAndTasks.Add(TAT);
}
var data = new List<SubjectPicker>();
for (int i = 0; i < Names.Count; i++) {
data.Add(new SubjectPicker(Names[i], Colors[i], Items[i], TestsAndTasks[i]));
}
return data;
}
public SubjectPicker(string name, Brush color, string itemstotal, List<TestOrTask> TestsAndTasks) {
PickerName = name;
PickerColor = color;
ItemTotal = itemstotal;
this.TestsAndTasks = TestsAndTasks;
}
public string PickerName { get; set; }
public Brush PickerColor { get; set; }
public string ItemTotal { get; set; }
public List<TestOrTask> TestsAndTasks = new List<TestOrTask>();
}
Xaml Code:
<Page.Resources>
<DataTemplate x:Key="SubjectTemplate">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Border Margin="0,9.5,0,0" Background="Transparent" >
<Rectangle Height="50" Width="50" Fill="{Binding PickerColor}" RadiusX="5" RadiusY="5"/>
</Border>
<StackPanel Grid.Column="1" Margin="14.5,0,0,0">
<TextBlock Text="{Binding PickerName}" Style="{ThemeResource ListViewItemTextBlockStyle}" />
<TextBlock Text="{Binding ItemTotal}" Style="{ThemeResource ListViewItemSubheaderTextBlockStyle}" />
</StackPanel>
</Grid>
</DataTemplate>
</Page.Resources>
<Page.BottomAppBar>
<CommandBar x:Name="AppBar" Visibility="Collapsed">
<AppBarButton x:Name="EditSubject" Icon="Edit" Label="Aanpassen" Click="EditSubject_Click"/>
<AppBarButton x:Name="DeleteSubject" Icon="Delete" Label="Verwijderen" Click="DeleteSubject_Click"/>
</CommandBar>
</Page.BottomAppBar>
<Grid x:Name="MainGrid" Loaded="MainGrid_Loaded">
<Controls:TopBarControl x:Name="TopBarControl" Margin="0" VerticalAlignment="Top" PageName="Vakken" ControlsVisible="All" Width="Auto" BackButtonClicked="TopBar_BackButtonClicked" AddButtonClicked="TopBar_AddButtonClicked" EditButtonClicked="TopBar_EditButtonClicked"/>
<Grid x:Name="ControlsGrid" Margin="0,50,0,-60" Tapped="ControlsGrid_Tapped">
<ListView x:Name="SubjectList" ItemsSource="{Binding}" ItemTemplate="{StaticResource SubjectTemplate}"/>
</Grid>
</Grid>
Void to iterate through:
private async Task SelectSubjects() {
for (int i = 0; i < SubjectList.Items.Count; i++) {
var control = SubjectList.Items[i];
Grid subject = control as Grid;
if (subject != null) {
subject.Background = new SolidColorBrush(SchoolToolsColors.AppColor);
await Task.Delay(TimeSpan.FromMilliseconds(50));
}
}
isSelecting = true;
AppBarVisible = Visibility.Visible;
}
Thanks in advance!!!
When iterating on databinded control you'll always get its underlying data.
You should Style.Triggers to alter UI based on data (changing background, showing/hiding controls, etc.).
However, there is a way to go with altering UI from C# but that would make XAML and code-behind tightly coupled => that introduces more complexity into your code - simply believe me, it is not what you want/need.
Related
I have a gridview with the name "majorGridView" inside a gridview with the name "assessmenGridView" whose data is data binding
XAML:
<GridView x:Name="asesmenGridView">
<GridView.ItemTemplate>
<DataTemplate>
<UserControl>
<Grid>
<StackPanel
x:Name="judulStack"
Height="40">
<TextBlock
x:Name="judulT"
Text="{Binding Title}"/>
</StackPanel>
<GridView
x:Name="majorGridView">
<GridView.ItemTemplate>
<DataTemplate>
<UserControl>
<Grid>
<TextBlock
x:Name="kelasT"
Text="{Binding Major}"/>
</Grid>
</UserControl>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
</Grid>
</UserControl>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
How to display binding text on "majorGridView" ? Because if I use the code below, I will get an error message: "The name 'majorGridView' does not exist in the current context"
Code:
ObservableCollection<Ujian> ujiandatasource = new ObservableCollection<Ujian>();
ObservableCollection<Ujian> majordatasource = new ObservableCollection<Ujian>();
string urlPath = "https://pto.study.id/api/" + ((App)(App.Current)).AsesmenCode + "-do/s2/choose-exam/" + guru.ID;
var httpClient = new HttpClient(new HttpClientHandler());
httpClient.DefaultRequestHeaders.Add("Authorization",
string.Format("Bearer {0}", tkn));
var response = await httpClient.GetAsync(urlPath);
string jsonText = await response.Content.ReadAsStringAsync();
try
{
JsonArray jsonArray = JsonArray.Parse(jsonText);
foreach (JsonValue groupValue in jsonArray)
{
JsonObject groupObject = groupValue.GetObject();
JsonArray majorArray = groupObject["majors"].GetArray();
foreach(JsonValue majorValue in majorArray)
{
JsonObject majorObject = majorValue.GetObject();
string major = majorObject["major"].GetString();
Ujian ujian1 = new Ujian();
ujian1.Major = major + ", ";
majordatasource.Add(ujian1);
majorGridView.ItemsSource = majordatasource;
}
Ujian ujian = new Ujian();
ujian.Title = title;
ujiandatasource.Add(ujian);
asesmenGridView.ItemsSource = ujiandatasource;
}
Ujian.cs
class Ujian
{
public string Title { get; set; }
public string Major { get; set; }
}
}
The name 'majorGridView' does not exist in the current context"
majorGridView in the parent DataTemplate, so we can't access majorGridView with name directly. For this scenario, we often use nested collection apply the value generally. And here is similar case that you could refer to.
I currently trying to change a cell's width if that row's data has a specified state. Each row displays a MediaRow with several columns, in case of an error (MediaRow's HasError = true) some columns should be hidden and the column 'status' should be enlarged and take the space of the now-hidden-columns.
Due to the requirement to have a user-defined order of the columns, I'm creating the columns programmatically.
Note: I removed several columns (and therefore properties of MediaRow) for readability.
MediaRow:
public class MediaRow : INotifyPropertyChanged
{
private string _status = string.Empty;
private string _barcode = string.Empty;
private string _medgrp = string.Empty;
private bool _infield = false;
private bool _haserror = false;
public string MedGrp
{
get => return _medgrp;
set { _medgrp = value; NotifyPropertyChanged(); }
}
public string Barcode
{
get => return _barcode;
set { _barcode = value; NotifyPropertyChanged(); }
}
public string Status
{
get => return _status;
set
{
_status = value; NotifyPropertyChanged();
HasError = (value.ToLower().StartsWith("error")) ? true : false;
}
}
public bool InField
{
get => return _infield;
set { _infield = value; NotifyPropertyChanged(); }
}
public bool HasError
{
get => return _haserror;
set { _haserror = value; NotifyPropertyChanged(); }
}
public string Description { get; set; }
}
create Columns:
private void PopulateColumns()
{
ObservableCollection<DataGridColumn> _loccolumns = new ObservableCollection<DataGridColumn>();
DataGridTextColumn barcodecolumn = new DataGridTextColumn();
barcodecolumn.Header = ResourceManagerService.GetResourceString("EasyTerminalClient_NG", "ColumnBarcode");
barcodecolumn.Width = new DataGridLength(Settings.Instance.CheckinColumnTable["barcode"], DataGridLengthUnitType.Star);
barcodecolumn.Binding = new Binding { Path = new PropertyPath("Barcode"), Mode = BindingMode.TwoWay };
barcodecolumn.Visibility = Visibility.Hidden;
barcodecolumn.HeaderStyle = new Style(typeof(System.Windows.Controls.Primitives.DataGridColumnHeader));
barcodecolumn.HeaderStyle.Setters.Add(new Setter(Control.HorizontalContentAlignmentProperty, HorizontalAlignment.Left));
barcodecolumn.HeaderStyle.Setters.Add(new Setter(Control.BackgroundProperty, System.Windows.Media.Brushes.Transparent));
barcodecolumn.HeaderStyle.Setters.Add(new Setter(Control.FontSizeProperty, new Binding { Path = new PropertyPath("headerSize"), Source = (EasyCheck.EasyTerminalClient_NG.Util.FontDetails)App.Current.FindResource("FontDetails") }));
DataGridTextColumn medgrpcolumn = new DataGridTextColumn();
medgrpcolumn.Header = ResourceManagerService.GetResourceString("EasyTerminalClient_NG", "ColumnMediaGroup");
medgrpcolumn.Width = new DataGridLength(Settings.Instance.CheckinColumnTable["mediagroup"], DataGridLengthUnitType.Star);
medgrpcolumn.Binding = new Binding { Path = new PropertyPath("MedGrp"), Mode = BindingMode.TwoWay };
medgrpcolumn.Visibility = Visibility.Hidden;
medgrpcolumn.HeaderStyle = new Style(typeof(System.Windows.Controls.Primitives.DataGridColumnHeader));
medgrpcolumn.HeaderStyle.Setters.Add(new Setter(Control.HorizontalContentAlignmentProperty, HorizontalAlignment.Left));
medgrpcolumn.HeaderStyle.Setters.Add(new Setter(Control.BackgroundProperty, System.Windows.Media.Brushes.Transparent));
medgrpcolumn.HeaderStyle.Setters.Add(new Setter(Control.FontSizeProperty, new Binding { Path = new PropertyPath("headerSize"), Source = (EasyCheck.EasyTerminalClient_NG.Util.FontDetails)App.Current.FindResource("FontDetails") }));
medgrpcolumn.CellStyle = new Style(typeof(DataGridCell));
medgrpcolumn.CellStyle.Setters.Add(new Setter(DataGridCell.VisibilityProperty, new Binding() { Path = new PropertyPath("HasError"), Mode = BindingMode.OneWay, Converter = new InverseBool2VisibilityConverter() }));
DataGridTextColumn statuscolumn = new DataGridTextColumn();
statuscolumn.Header = ResourceManagerService.GetResourceString("EasyTerminalClient_NG", "ColumnState");
statuscolumn.Width = new DataGridLength(Settings.Instance.CheckinColumnTable["state"], DataGridLengthUnitType.Star);
statuscolumn.Binding = new Binding() { Path = new PropertyPath("Status"), Mode = BindingMode.OneWay, Converter = new LanguageConverter(), FallbackValue = "???" };
statuscolumn.Visibility = Visibility.Hidden;
statuscolumn.HeaderStyle = new Style(typeof(System.Windows.Controls.Primitives.DataGridColumnHeader));
statuscolumn.HeaderStyle.Setters.Add(new Setter(Control.HorizontalContentAlignmentProperty, HorizontalAlignment.Left));
statuscolumn.HeaderStyle.Setters.Add(new Setter(Control.BackgroundProperty, System.Windows.Media.Brushes.Transparent));
statuscolumn.HeaderStyle.Setters.Add(new Setter(Control.FontSizeProperty, new Binding { Path = new PropertyPath("headerSize"), Source = (EasyCheck.EasyTerminalClient_NG.Util.FontDetails)App.Current.FindResource("FontDetails") }));
statuscolumn.CellStyle = new Style(typeof(DataGridCell));
//statuscolumn.CellStyle.Setters.Add(new Setter(DataGridCell.MarginProperty, "-5,-5,-5,0"));
//statuscolumn.CellStyle.Setters.Add(new Setter(DataGridCell.ActualWidthProperty, 500.0));
if (Settings.Instance.CheckinColumnSequence != null)
{
//string columnnames = "number|barcode|title|mediagroup|branch|expires|fee|state|imagestate|";
string[] columnSequence = Settings.Instance.CheckinColumnSequence;
for (int i = 0; i < columnSequence.Length; i++)
{
DataGridColumn thiscolumn = null;
switch (columnSequence[i])
{
case "barcode":
thiscolumn = barcodecolumn;
break;
case "mediagroup":
thiscolumn = medgrpcolumn;
break;
case "state":
thiscolumn = statuscolumn;
break;
}
if (thiscolumn != null)
{
thiscolumn.Visibility = Visibility.Visible;
thiscolumn.DisplayIndex = i;
_loccolumns.Add(thiscolumn);
}
}
ColumnCollection = _loccolumns;
}
}
XAML:
<UserControl.Resources>
<DataTemplate x:Key="RowDetailTemplate">
<Grid x:Name="RowDetailGrid"
Width="952"
Height="Auto"
Margin="5">
<Border HorizontalAlignment="Left"
VerticalAlignment="Top"
CornerRadius="5">
<Border.Background>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStop Offset="0" Color="WhiteSmoke" />
<GradientStop Offset="0.75" Color="#AAFFFFAA" />
<GradientStop Offset="1" Color="#AAFFD455" />
</LinearGradientBrush>
</Border.Background>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0"
Margin="10"
HorizontalAlignment="Center"
FontSize="{Binding headerSize, Source={StaticResource FontDetails}}"
FontWeight="Black"
Text="Weitere Details" />
<TextBlock Grid.Row="1"
Margin="10"
HorizontalAlignment="Left"
Text="{Binding Description}"
TextWrapping="WrapWithOverflow" />
</Grid>
</Border>
<Border Margin="0,0,0,0" CornerRadius="5">
<Border.Background>
<RadialGradientBrush Center="0.5,1" GradientOrigin="0,1" Opacity="0.3" RadiusX="0.8" RadiusY="0.8">
<GradientStop Offset="1" Color="#AACCCCCC" />
<GradientStop Offset="1" Color="WhiteSmoke" />
</RadialGradientBrush>
</Border.Background>
</Border>
</Grid>
</DataTemplate>
</UserControl.Resources>
<DataGrid x:Name="dataGrid1"
Margin="10,10,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
AlternationCount="2"
AutoGenerateColumns="False"
c:DataGridColumnsBehavior.BindableColumns="{Binding ColumnCollection, UpdateSourceTrigger=PropertyChanged}"
ItemsSource="{Binding MediaRowCollection, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged }"
MinRowHeight="26"
RowDetailsTemplate="{StaticResource RowDetailTemplate}"
RowDetailsVisibilityChanged="dataGrid1_RowDetailsVisibilityChanged"
Loaded="dataGrid1_Loaded"
Width="952"
IsReadOnly="True"
SelectionMode="Single"
CanUserReorderColumns="False"
CanUserResizeColumns="False"
CanUserSortColumns="False"
CanUserResizeRows="False"
HorizontalScrollBarVisibility="Disabled"
AreRowDetailsFrozen="True"
HeadersVisibility="Column" VerticalScrollBarVisibility="Auto" >
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger Binding="{Binding InField}" Value="False">
<Setter Property="Background" Value="Transparent"/>
</DataTrigger>
<DataTrigger Binding="{Binding InField}" Value="True">
<Setter Property="Background" Value="#ffffffac"/>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
<DataGrid.RowHeaderTemplate>
<DataTemplate>
<ToggleButton x:Name="RowHeaderToggleButton"
Click="ToggleButton_Click"
Cursor="Hand"/>
</DataTemplate>
</DataGrid.RowHeaderTemplate>
</DataGrid>
In the first steps I ignored the HasError-condition and just tried to apply the desired effect to the status-cells but with no success. I'm just getting an unhandled exception. (The respective code I left as comments in the 'Create Columns' -Section.)
System.ArgumentException: '"-5,-5,-5,0" ist kein gültiger Wert für die
Eigenschaft "System.Windows.FrameworkElement.Margin" auf einem
"Setter".'
should translate to:
System.ArgumentException: '"-5,-5,-5,0" is no valid Value for the property "System.Windows.FrameworkElement.Margin" on a "Setter".'
Question:
How can I achieve the desired effect?
If MediaRow's HasError == true the MedGrp-cell should be hidden and the Status-cell should take up the MedGrp-cells's space.
I'd be happy about any suggestions, even if it is only for a fixed-value for the new status-width.
You can't set the Margin property to a string. You should set it to a Thickness:
statuscolumn.CellStyle.Setters.Add(new Setter(DataGridCell.MarginProperty, new Thickness(-5,-5,-5,0))));
This should get rid of the ArgumentException you are getting.
I have an image binding on gridview with XAML below:
<Border x:Name="coverBox" Grid.Row="0" Margin="5,10,0,0" Width="230" Height="170" VerticalAlignment="Top" HorizontalAlignment="Left" BorderBrush="Gray" BorderThickness="1" Background="{x:Null}">
<Image x:Name="cover" Source="{Binding Thumbnail}" HorizontalAlignment="Center" Stretch="Uniform" AutomationProperties.Name="{Binding Title}" Width="230" Height="170"/>
</Border>
Code:
string urlPath1 = "http://..../API/sekolah";
var httpClient1 = new HttpClient(new HttpClientHandler());
var values1 = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("api_key", "...."),
new KeyValuePair<string, string>("limit", limit++.ToString()),
new KeyValuePair<string, string>("hal", noHal++.ToString())
};
var response1 = await httpClient1.PostAsync(urlPath1, new FormUrlEncodedContent(values1));
response1.EnsureSuccessStatusCode();
if (!response1.IsSuccessStatusCode)
{
busyIndicator.IsActive = false;
RequestException();
}
string jsonText1 = await response1.Content.ReadAsStringAsync();
JsonObject jsonObject1 = JsonObject.Parse(jsonText1);
JsonArray jsonData1 = jsonObject1["data"].GetArray();
foreach (JsonValue groupValue1 in jsonData1)
{
JsonObject groupObject2 = groupValue1.GetObject();
string thumbnail = groupObject2.ContainsKey("thumbnail") && groupObject2["thumbnail"] != null ? groupObject2["thumbnail"].GetString() : string.Empty;
ListingClass file1 = new ListingClass();
file1.Thumbnail = thumbnail;
listingDatasourceDetail.Add(file1);
}
listingGridView.ItemsSource = listingDatasourceDetail;
I want while still loading to take the image data from JSON, then show the paceholder images/SEKOLAH-place-holder-600.png first
How to add placeholder while still loading?
Wrap your cover Image within a Grid, then create another Image to display the placeholder png and place it behind cover.
Try add Loading event to Image :
private void myimage_Loading(FrameworkElement sender, object args)
{
Image myimage = (Image)sender;
myimage.Source = new BitmapImage(new Uri("ms-appx:///images/SEKOLAH-place-holder-600.png"));
}
i have a huge problem....
i have a MainWindow.xaml. this xaml is seperated into differnt columns and rows. in. on the left side i have my different buttons. on the right side i have my so called content grid. in this content grid i open my different user controls by pressing a button.
in one of these user controls i request a route from A to B. if the points are excatly identified the route gets displays in the listbox below the input screen.
but if one of the two points isn't exactly identified i open a new window with two comboboxes where you have to specify and select your inputs. after choosing your start and destination points. the window should be closed by pressing the button OK and in the listbox in the user control the route should bey displayed....but it doesn't...
my english isn't that good and i hope you can help me by posting the code..
The Code behind file of the User Control:
RoutenplanungSelection rps = new RoutenplanungSelection();
public void checkStationsnamenSindEindeutig(string von, string nach, string datum, string zeit, bool abfahrt)
{
WebClient wc = new WebClient();
wc.Encoding = Encoding.UTF8;
string data = wc.DownloadString(....url);
var xe = XElement.Parse(data);
var CountOrigins = from a in xe.Descendants("itdOdv")
where a.Attribute("usage").Value == "origin"
select a.Element("itdOdvName").Elements("odvNameElem").Count();
var CountDestinations = from a in xe.Descendants("itdOdv")
where a.Attribute("usage").Value == "destination"
select a.Element("itdOdvName").Elements("odvNameElem").Count();
int countorigins = 0;
foreach (var c in CountOrigins)
countorigins = Convert.ToInt32(c);
int countdestinations = 0;
foreach (var c in CountDestinations)
countdestinations = Convert.ToInt32(c);
if (countorigins == 1 && countdestinations == 1)
{
downloadEindeutigenXml(von, nach, datum, zeit, abfahrt);
}
if (countorigins > 1 || countdestinations > 1)
{
var getAllOrigins = from a in xe.Descendants("itdOdv")
where a.Attribute("usage").Value == "origin"
select a;
var getAllDestinations = from a in xe.Descendants("itdOdv")
where a.Attribute("usage").Value == "destination"
select a;
foreach(var r in getAllOrigins)
rps.uebergebeXmlOrigins(r);
foreach (var r in getAllDestinations)
rps.uebergebeXmlDestination(r);
rps.uebergebeAllgemeineInfos(datum, zeit, abfahrt);
rps.Show();
}
}
public async void downloadEindeutigenXml(string von, string nach, string datum, string zeit, bool abfahrt)
{
WebClient wc = new WebClient();
wc.Encoding = Encoding.UTF8;
if(abfahrt)
{
this.mw = (MainWindow)Application.Current.MainWindow;
mw.progress.IsIndeterminate = false;
mw.progress.IsIndeterminate = true;
formatEindeutigeData(XElement.Parse(await wc.DownloadStringTaskAsync(
"....url")));
mw.progress.IsIndeterminate = false;
}
else
{
this.mw = (MainWindow)Application.Current.MainWindow;
mw.progress.IsIndeterminate = false;
mw.progress.IsIndeterminate = true;
formatEindeutigeData(XElement.Parse(await wc.DownloadStringTaskAsync(
"....url")));
mw.progress.IsIndeterminate = false;
}
}
private string addZeros(string number)
{
if (number.Length < 2)
return number.Insert(0, "0");
else
return number;
}
private void formatEindeutigeData(XElement xml)
{
box.Items.Clear();
var checkConnections = (from a in xml.Descendants("itdMessage")
where a.Attribute("code").Value == "-4000"
select a).Count();
var checkDateValid = (from a in xml.Descendants("itdMessage")
where a.Attribute("code").Value == "-4001"
select a).Count();
if (checkConnections == 1)
{
TextBlock nothing = new TextBlock();
nothing.TextAlignment = TextAlignment.Center;
nothing.HorizontalAlignment = HorizontalAlignment.Center;
nothing.FontSize = 18;
nothing.Text = "\n\n\nLeider gibt es keine Verbindung zu Ihrem gewünschten Ziel! :-(";
box.Items.Add(nothing);
}
if (checkDateValid == 1)
{
TextBlock nothing = new TextBlock();
nothing.TextAlignment = TextAlignment.Center;
nothing.HorizontalAlignment = HorizontalAlignment.Center;
nothing.FontSize = 18;
nothing.Text = "\n\n\nDatum außerhalb der Fahrplanperiode! :-(";
box.Items.Add(nothing);
}
var result = (from a in xml.Descendants("itdRouteList").Elements("itdRoute")
select new
{
partialRoute = from b in a.Descendants("itdPartialRouteList").Elements("itdPartialRoute")
select new
{
von = from c in b.Elements("itdPoint")
where c.Attribute("usage").Value == "departure"
select new
{
station = c.Attribute("name").Value,
abfahrtdatum_jahr = c.Element("itdDateTimeTarget").Element("itdDate").Attribute("year").Value,
abfahrtdatum_monat = c.Element("itdDateTimeTarget").Element("itdDate").Attribute("month").Value,
abfahrtdatum_tag = c.Element("itdDateTimeTarget").Element("itdDate").Attribute("day").Value,
abfahrtdatum_stunde = addZeros(c.Element("itdDateTimeTarget").Element("itdTime").Attribute("hour").Value),
abfahrtdatum_minute = addZeros(c.Element("itdDateTimeTarget").Element("itdTime").Attribute("minute").Value)
},
nach = from c in b.Elements("itdPoint")
where c.Attribute("usage").Value == "arrival"
select new
{
station = c.Attribute("name").Value,
ankuftdatum_jahr = c.Element("itdDateTimeTarget").Element("itdDate").Attribute("year").Value,
ankuftdatum_monat = c.Element("itdDateTimeTarget").Element("itdDate").Attribute("month").Value,
ankuftdatum_tag = c.Element("itdDateTimeTarget").Element("itdDate").Attribute("day").Value,
ankuftdatum_stunde = addZeros(c.Element("itdDateTimeTarget").Element("itdTime").Attribute("hour").Value),
ankuftdatum_minute = addZeros(c.Element("itdDateTimeTarget").Element("itdTime").Attribute("minute").Value)
},
fahrmittel = from c in b.Elements("itdMeansOfTransport")
select new
{
name_plus_linie = c.Attribute("name").Value,
linie = c.Attribute("shortname").Value,
symbol = c.Attribute("symbol").Value,
richtung = c.Attribute("destination").Value
}
},
fahrzeit = a.Element("seqRoutes").Element("seqRoute").Attribute("publicDuration").Value
}).ToList();
foreach (var r in result)
{
foreach (var q in r.partialRoute)
{
foreach (var s in q.von)
{
foreach (var t in q.nach)
{
foreach (var a in q.fahrmittel)
{
//MessageBox.Show("von: " + s.ToString() + " nach: " + t.ToString() + " mittels " + a.name_plus_linie + " richtung " + a.richtung + "fahrzeit: " + r.fahrzeit);
TextBlock tb_name_linie_richtung = new TextBlock();
tb_name_linie_richtung.FontSize = 18;
if (a.name_plus_linie != "" && a.richtung != "")
tb_name_linie_richtung.Text = a.name_plus_linie + ", Richtung " + a.richtung;
else
tb_name_linie_richtung.Text = "Fußweg";
box.Items.Add(tb_name_linie_richtung);
}
TextBlock uhrzeit_von = new TextBlock();
uhrzeit_von.Text = s.abfahrtdatum_stunde + ":" + s.abfahrtdatum_minute + " " + s.station;
box.Items.Add(uhrzeit_von);
TextBlock uhrzeit_nach = new TextBlock();
uhrzeit_nach.Text = t.ankuftdatum_stunde + ":" + t.ankuftdatum_minute + " " + t.station;
box.Items.Add(uhrzeit_nach);
}
}
}
box.Items.Add(new TextBlock().Text = "\n\n");
}
}
XAML of the user control:
<UserControl x:Class="WLive.Routenplanung"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:toolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input.Toolkit"
xmlns:Controls="http://metro.mahapps.com/winfx/xaml/controls"
xmlns:ControlsExtended="http://schemas.xceed.com/wpf/xaml/toolkit"
xmlns:local="clr-namespace:WLive">
<UserControl.Resources>
<local:FontSizeConverter x:Key="fontSizeCon" />
</UserControl.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="8*"/>
<ColumnDefinition Width="92*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="11*"/>
<RowDefinition Height="11*"/>
<RowDefinition Height="8*" />
<RowDefinition Height="10*"/>
<RowDefinition Height="8*"/>
<RowDefinition Height="52*"/>
</Grid.RowDefinitions>
<Label Content="Von: " Grid.Column="0" FontSize="18" Grid.Row="0" />
<toolkit:AutoCompleteBox x:Name="tbvon" Grid.Row="0" Grid.Column="1" FilterMode="Contains" MinimumPrefixLength="4"
FontSize="{Binding Path=ActualHeight, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Grid}, Converter={StaticResource fontSizeCon}}" TextChanged="routevon_TextChanged"/>
<Label Content="Nach: " Grid.Column="0" FontSize="18" Grid.Row="1"/>
<toolkit:AutoCompleteBox x:Name="tbnach" Grid.Row="1" Grid.Column="1" FilterMode="Contains" MinimumPrefixLength="4"
FontSize="{Binding Path=ActualHeight, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Grid}, Converter={StaticResource fontSizeCon}}" TextChanged="routenach_TextChanged"/>
<RadioButton x:Name="radioabf" Grid.Row="2" Grid.ColumnSpan="2" Content="Abfahrt" FontSize="18" IsChecked="True"/>
<RadioButton x:Name="radioank" Grid.Row="2" Grid.ColumnSpan="2" Content="Ankunft" FontSize="18" Margin="100 0 0 0"/>
<StackPanel Grid.Row="3" Grid.ColumnSpan="2">
<ControlsExtended:DateTimePicker x:Name="datumsscheisse"></ControlsExtended:DateTimePicker>
</StackPanel>
<Button x:Name="butabfragen" Grid.Row="4" Grid.ColumnSpan="2" FontSize="18" Content="Route berechnen" HorizontalAlignment="Right" Click="abfragen_Click" />
<ListBox x:Name="box" Grid.Row="5" Grid.ColumnSpan="2">
</ListBox>
</Grid>
the code behind file of the routenplanungSelection
private string datum;
public string Datum
{
get { return datum; }
set { datum = value; }
}
private string zeit;
public string Zeit
{
get { return zeit; }
set { zeit = value; }
}
private bool abfahrt;
public bool Abfahrt
{
get { return abfahrt; }
set { abfahrt = value; }
}
public RoutenplanungSelection()
{
InitializeComponent();
}
public void uebergebeXmlOrigins(XElement xml)
{
var getAllOrigins = from a in xml.Descendants("odvNameElem")
select new
{
id = a.Attribute("id").Value,
name = a.Value
};
foreach (var r in getAllOrigins)
{
comboabfahrt.ItemsSource = getAllOrigins;
}
}
public void uebergebeXmlDestination(XElement xml)
{
var getAllDestinations = from a in xml.Descendants("odvNameElem")
select new
{
id = a.Attribute("id").Value,
name = a.Value
};
foreach (var r in getAllDestinations)
{
comboziel.ItemsSource = getAllDestinations;
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
string abfahrtid = comboabfahrt.SelectedValue.ToString();
string zielid = comboziel.SelectedValue.ToString();
new Routenplanung().downloadEindeutigenXml(abfahrtid, zielid, Datum, Zeit, Abfahrt);
}
public void uebergebeAllgemeineInfos(string datum, string zeit, bool abfahrt)
{
Datum = datum;
Zeit = zeit;
Abfahrt = abfahrt;
}
XAML of the window:
<Controls:MetroWindow x:Class="WLive.RoutenplanungSelection"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Controls="http://metro.mahapps.com/winfx/xaml/controls"
Title="WLive - Routenplanung, Haltestellenspezifikation" Height="230" Width="400" MinHeight="230" MinWidth="400">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="15*"/>
<ColumnDefinition Width="85*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="1*"/>
<RowDefinition Height="1*"/>
<RowDefinition Height="1*"/>
<RowDefinition Height="1*"/>
</Grid.RowDefinitions>
<Label Content="Bitte spezifizieren Sie Ihre Eingaben:" FontSize="18" Foreground="Red" FontWeight="Bold" Grid.Row="0" Grid.Column="1"/>
<Label Content="Von:" Grid.Column="0" Grid.Row="1" FontSize="24" HorizontalContentAlignment="Center" VerticalContentAlignment="Center"/>
<Label Content="Nach:" Grid.Column="0" Grid.Row="2" FontSize="20" HorizontalContentAlignment="Center" VerticalContentAlignment="Center"/>
<ComboBox x:Name="comboabfahrt" Grid.Column="1" Grid.Row="1" DisplayMemberPath="name" SelectedValuePath="id" SelectedIndex="0" />
<ComboBox x:Name="comboziel" Grid.Column="1" Grid.Row="2" DisplayMemberPath="name" SelectedValuePath="id" SelectedIndex="0" />
<Button Grid.Row="3" Margin="0 5 5 5" HorizontalAlignment="Right" FontSize="20" Grid.Column="1" Click="Button_Click">OK</Button>
</Grid>
my aim is if the new window appears, i specifiy my station, the i click on OK, the window closes and in the listbox my result gets displays.
everything works, cause if i say MessageBox.Show(xml.ToString()); in the formatData(XElement xml) Method it displays me the right xml file...but it doesn't appear in the listbox....
Take a look to the Button_Click method of your RoutenplanungSelection window: first you retrive a couple of selected values, then you create a new instance of Routenplanung window.
Of course that new instance is not the same instance of the main window you see on the screen. In your secondary window you should have a reference to the main one.
listpicker shows object name instead of property.I'm already try all the solution which already given in stackoverflow but i dn't get any result
BorderThickness="0.2" SelectionMode="Multiple" SelectionChanged="AreaClassification_SelectionChanged"
VerticalAlignment="Bottom" Margin="204,-53,0,0" BorderBrush="Black" >
<toolkit:ListPicker.ItemTemplate>
<DataTemplate>
<StackPanel >
<TextBlock Text="{Binding name}" Foreground="Black" FontSize="18"/>
</StackPanel>
</DataTemplate>
</toolkit:ListPicker.ItemTemplate>
<toolkit:ListPicker.FullModeItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding name}" FontSize="18" Foreground="White" />
</StackPanel>
</DataTemplate>
</toolkit:ListPicker.FullModeItemTemplate>
</toolkit:ListPicker>
I just need to learn how to design a control.any reference do you have?
CodeBehind
string result = e.Result;
JObject o = JObject.Parse(result);
var results = o["Data"]["Area"];
JArray obj = results as JArray;
var dt = obj.ToArray();
foreach (var d in dt)
{
Area dts = new Area();
dts.code = Convert.ToString(d["code"]);
dts.name = Convert.ToString(d["name"]);
_lst.Add(dts);
}
AreaClassification.ItemsSource = _lst;
After lot of research i found this
AreaClassification.SummaryForSelectedItemsDelegate += SummarizeTeams;
protected string SummarizeTeams(IList selection)
{
string str = "*None Selected*";
if (null != selection && selection.Count > 0)
{
StringBuilder contents = new StringBuilder();
int idx = 0;
foreach (object o in selection)
{
if (idx > 0) contents.Append(", ");
contents.Append(((Area)o).name);
idx++;
}
str = contents.ToString();
}
return str;
}
To Show List Of Item We Need to use SummaryForSelectedItemsDelegate method on c#.I hope It's will help others