Hey I have a question about getting an ContactTypeId from the ContactType. This is the object that has an id:
public class ContactType
{
public int ContactTypeId { get; set; }
public string ContactTypeValue { get; set; }
public int ContactId { get; set; }
public DateTime? Added { get; set; }
public DateTime? Updated { get; set; }
public DateTime? Deleted { get; set; }
}
I wrote a WPF application that has a listbox.
<ComboBox x:Name="ContactTypeComboBox" HorizontalAlignment="Left" Margin="110,68,0,0" VerticalAlignment="Top" Width="120" ItemsSource="{Binding ContactTypes}" DisplayMemberPath="ContactTypeValue" SelectedValuePath="ContactTypeId" />
If i get Selected value path doesn't give an ContactTypeId from that object. It only gives a string "ContactTypeId"
Please help me to get a ContactTypeId from ContactType
SelectedValuePath tells the control how to drill down into the selected item and extract a value. The value for the selected item (in this case, its ContactTypeId) is exposed as SelectedValue. That's the property you want to read.
Related
I have two related entities:
public class Event
{
public string ID { get; set; }
public DateTime EventDate { get; set; }
public string EventData { get; set; }
public string DocID1 { get; set; }
public int DocID2 { get; set; }
public virtual Document Document1 { get; set; }
public virtual Document Document2 { get; set; }
}
public class Document
{
public string ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Number { get; set; }
}
Also created List to display data in WPF:
private ObservableCollection<Event> eventList;
public ObservableCollection<Event> EventList
{
get { return eventList; }
set
{
if (value != eventList)
{
eventList = value;
}
RaisePropertyChanged(nameof(EventList));
}
}
data for my EventList is taken from entity Event:
var query = DBContext.Events.Select(x => x).AsQueryable();
EventList = query.ToList();
What I need is how to set GridControl Column "colFirstName" value to be equal "Document1.FirstName" if DocID1 is not null and "Document2.FirstName" if DocID2 is not null. My XAML code for GridControl is below, could You help how to do it in Xaml, not in ViewModel, or if there is no way to do it in Xaml, what is the best way to do it in ViewModel.
<dxg:GridControl AutoPopulateColumns="False"
ItemsSource="{Binding EventList, UpdateSourceTrigger=PropertyChanged}">
<dxg:GridControl.Columns>
<dxg:GridColumn
x:Name="colEventData"
Width="120"
FieldName="EventData"
Header =" Event data"
Visible="True" >
</dxg:GridColumn>
<dxg:GridColumn
x:Name="colFirsnName"
Width="120"
FieldName="Document1.FirstName"
Header="First Name"
Visible="True"
VisibleIndex="1" />
</dxg:GridControl.Columns>
</dxg:GridControl>
You can use the UnboundExpression property to create a column with a custom expression. For example, to conditionally show values from different properties, use the Iif function:
<dxg:GridColumn FieldName="CustomColumn" x:Name="colFirsnName"
UnboundExpression="Iif(IsNullOrEmpty([DocID1]), [Document2.FirstName], [Document1.FirstName])"
UnboundType="String"/>
This kind of logic should be implemented in the model or view model class. Remember that XAML is only a markup language.
Just create another property that returns the first match and bind to this one. If your entity classes are auto-generated, you could create a new partial class:
public partial class Event
{
public string DocName
{
get
{
if (Document1 != null)
return Document1.FirstName;
if (Document2 != null)
return Document1.LastName;
return null;
}
}
}
<dxg:GridColumn
x:Name="colFirsnName"
Width="120"
FieldName="DocName"
Header="First Name"
Visible="True"
VisibleIndex="1" IsReadOnly="true" />
I'm binding an editable (you can type in it to add items to the list of choices) radcombobox in a column of a radgridview. It is not throwing a binding error, but it is not updating the bound property (Model.Remarks)
Here are the classes
public class NotamRemarkList : List<string>
{
public NotamRemarkList()
{
Add("Precision approaches are down; higher weather minimums apply.");
Add("Due to runway closure, approaches available have higher minimums.");
Add("All approaches are down; weather must be VFR.");
Add("Long runway is closed; issue if the other runways are wet.");
Add("Runway shortened; issue if wet.");
Add("Airport will be closed at the time we are scheduled in.");
Add("Runway lights are inoperative; night flights prohibited.");
}
}
public class NotamViewModel
{
[DataMember]
public string NewStatus { get; set; }
[DataMember]
public Notam Model { get; set; }
[DataMember]
public string NotamGroup { get; set; }
[DataMember]
public int NotamCount { get; set; }
[DataMember]
public DateTime? EarliestNotamDepartureTime { get; set; } // min_dep_datetime
[DataMember]
public string RadioButtonGroupName { get; set; }
}
public class Notam
{
[DataMember]
public string Remarks { get; set; }
[DataMember]
public string TripNumber { get; set; }
[DataMember]
public string ArrivalDeparture { get; set; }
}
Here's the xaml I have tried for the column - the first one uses a cell template, the second attempts to do everything in a column
<telerik:GridViewDataColumn Header="Remarks" IsFilterable="False" IsSortable="False" IsReadOnly="False" Width="430">
<telerik:GridViewDataColumn.CellTemplate>
<DataTemplate>
<telerik:RadComboBox SelectedValue="{Binding Model.Remarks, Mode=TwoWay}" ItemsSource="{StaticResource NotamRemarkList}" IsEditable="True"/>
</DataTemplate>
</telerik:GridViewDataColumn.CellTemplate>
</telerik:GridViewDataColumn>
<telerik:GridViewComboBoxColumn SelectedValueMemberPath="Model.Remarks" UniqueName="colRemarks" IsComboBoxEditable="true" IsFilterable="False" IsSortable="False"/>
public class Notam:INotifyPropertyChanged
{
private string _remarks;
[DataMember]
public string Remarks
{
get {return _remarks;}
set{
_remarks=value ;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("Remarks"));
}
}
[DataMember]
public string TripNumber { get; set; }
[DataMember]
public string ArrivalDeparture { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
}
<telerik:RadComboBox SelectedValue="{Binding Model.Remarks, Mode=TwoWay}" SelectedValueMemberPath="Model.Remarks" ItemsSource="{StaticResource NotamRemarkList}" IsEditable="True"/>
I hope this will help.
I've been sitting on this problem for hours now,
I've got this partial xaml code:
<TextBlock Text="{Binding temprature}" Height="30" HorizontalAlignment="Left" Margin="13,119,0,0" Name="textBlock1" VerticalAlignment="Top" Width="68" />
<TextBlock Height="30" HorizontalAlignment="Left" Name="commentsTextBlock" Text="Comments:" VerticalAlignment="Bottom" Margin="12,0,0,-31" />
<ListBox Margin="2,785,-14,-33" ItemsSource="{Binding comments}" DataContext="{Binding}" Name="commentsListBox">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="0,0,0,17">
<StackPanel Width="311">
<TextBlock Text="{Binding poster_username}" TextWrapping="NoWrap" Style="{StaticResource PhoneTextSubtleStyle}" TextTrimming="WordEllipsis" Width="Auto" Foreground="White" FontFamily="Segoe WP Semibold" />
<TextBlock Text="{Binding comment_text}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}" TextTrimming="WordEllipsis" MaxHeight="100" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And I have this class (Thread) which include a List of comments that should be displayed in the ListBox.
public class Thread : INotifyPropertyChanged
{
public string title { get; set; }
public string deal_link { get; set; }
public string mobile_deal_link { get; set; }
public string deal_image { get; set; }
public string deal_image_highres { get; set; }
public string description { get; set; }
public string submit_time { get; set; }
public bool hot_date { get; set; }
public string poster_name { get; set; }
public double temperature { get; set; }
public double price { get; set; }
public int timestamp { get; set; }
public string expired { get; set; }
public Forum forum { get; set; }
public Category category { get; set; }
public object merchant { get; set; }
public object tags { get; set; }
public int thread_id { get; set; }
public string visit_link { get; set; }
public string hot_time { get; set; }
public int comment_count { get; set; }
public string availability { get; set; }
public string can_vote { get; set; }
public string seen { get; set; }
public List<Comment> comments { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
public void Convert2Unicode()
{
UnicodeEncoding unicode = new UnicodeEncoding();
Byte[] encodedBytes = unicode.GetBytes(title);
title = String.Format("[{0}]", title);
}
private void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public void SetComments(string content)
{
PaginatedComments commentsList;
this.comments.Clear();
DataContractJsonSerializer serializer =
new DataContractJsonSerializer(typeof(PaginatedComments));
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(content)))
{
commentsList = (PaginatedComments)serializer.ReadObject(ms);
}
foreach (var thread in commentsList.data.comments)
{
this.comments.Add(thread);
}
}
public Thread()
{
comments = new List<Comment>();
}
public void addComments()
{
List<string> parameters = new List<string>();
parameters.Add("thread_id=" + thread_id);
parameters.Add("results_per_page=10");
parameters.Add("page=1");
// Set the data context of the listbox control to the sample data
APICalls.makeRequest(APICalls.ViewingPaginatedComments, parameters, SetComments);
}
//
// Sets the "Seen" variable depending if the item is new (since the last time the application was opened
//
public void updateNewItems()
{
try
{
int last_seen = (int)IsolatedStorageSettings.ApplicationSettings["lastrun"];
if (last_seen < timestamp)
{
seen = "New";
}
else
{
seen = "";
}
}
catch (System.Exception e)
{
IsolatedStorageSettings.ApplicationSettings["lastrun"] = APICalls.GetIntTimestamp();
IsolatedStorageSettings.ApplicationSettings.Save();
MessageBox.Show(e.Message);
}
IsolatedStorageSettings.ApplicationSettings["lastrun"] = APICalls.GetIntTimestamp();
IsolatedStorageSettings.ApplicationSettings.Save();
}
}
public class Comment
{
public string poster_username { get; set; }
public string post_date { get; set; }
public string comment_text { get; set; }
public int timestamp { get; set; }
public int like_count { get; set; }
public string comment_edit_text { get; set; }
}
public class CommentData
{
public List<Comment> comments { get; set; }
public int comment_count { get; set; }
public int total_comments { get; set; }
}
public class PaginatedComments
{
public string response_status { get; set; }
public CommentData data { get; set; }
}
If I load the comments into the Thread before changing the DataCotext to this specific thread. the comments are shown, but when I update the comments after changing the DataContext and navigating to the page the comments are not shown (I have other fields in the rest of the xaml page that are binded to the same instance and they work perfectly. only the comments don't work!
I really appreciate your help!
Thanks
You should be using
public ObservableCollection<Comment> comments{ get; set;}
instead of
public List<Comment> comments { get; set; }
The ObservableCollection sends update notices to the view anytime one of the items(in this case a Comment ) is added or removed.
Note: It won't update the Comment . To have the items bound to the Comment update, Comment has to implement INotifyPropertyChanged.
Your property is a simple List<T>. Silverlight needs to be signaled when something changes, using events.
A List<T> does not raise any event when items are being added/removed, so Silverlight cannot detect the new items and thus does not update the UI. The simplest way to make this work is usually to use an ObservableCollection<T> instead of a list.
This collection will raise events that Silverlight knows to listen to.
Please note that for this to work you should not call Add/Remove/Clear from any other thread than the U/I (Dispatcher) thread, since Silverlight controls are not thread-safe (and the events are raised on the thread that performs the Add/Remove/Clear call). To do that, simply make sure you call Dispatcher.BeginInvoke from your SetComments method (since it seems to be a callback happening from whatever your fetching mechanism is).
Alternatively, you could also regenerate a brand new List object when fetching comments, and raise the NotifyPropertyCHanged event in the SetComments method, but that would lead to losing the current selection and resetting your list to the top, which is probably not what you want to do.
My page's data context is set to an Instance of a Project class and all of the other fields in the page are working properly. Each project has another class associated with it as a property. This represents data from another company that we are integrating into this page.
I am attempting to bind to this sub object's TypeID property. Here is a sketch of the objects.
public class Project
{
public int Id { get; set; }
public string ProjectName { get; set; }
public ABCProject ABCProject { get; set; }
}
public class ABCProject
{
public int Id { get; set; }
public int ABCProjectTypeId { get; set; }
public ABCProjectType { get; set; }
}
public class ABCProjectType
{
public int ProjectTypeId { get; set; }
public string TypeName { get; set; }
}
Here is what my XAML looks like:
<telerik:RadComboBox Grid.Column="2" Grid.Row="1" telerik:StyleManager.Theme="Metro" x:Name="ProjectTypeCombo"
ItemsSource="{Binding ProjectTypePickList}"
SelectedValue="{Binding ABCProject.ABCProjectTypeId, Mode=TwoWay}"
SelectedValuePath="ABCProjectTypeId"
DisplayMemberPath="TypeName"/>
The pick list is being bound properly. The issue is that the selected value and selected value path don't seem to be binding as I get a blank combobox when the page loads.
I have two classes,
public class BookItem
{
public string BookID { get; set; }
public string ItemID { get; set; }
public Item Item { get; set; }
public ItemType Type { get; set; }
public string ParentID { get; set; }
public string BoxID { get; set; }
public string StyleID { get; set; }
public string NotesID { get; set; }
public string Code_XAML { get; set; }
public string Description_XAML { get; set; }
public CompositeCollection SubItems { get; set; }
}
public class Item : ClaunchBaseClass
{
public string ItemID { get; set; }
public int Type { get; set; }
public string Code { get; set; }
public string Description { get; set; }
private BookList _books = new BookList();
public BookList Books { get {return _books;} set { _books = value; }}
}
and I've created the following XAML:
<pre>
<TreeView Name="tvList" Grid.Row="2" MouseDoubleClick="tvList_MouseDoubleClick">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate DataType="x:Type j:BookItem" ItemsSource="{Binding SubMenu}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Item.Code}" Grid.Column="0" />
<TextBlock Text="{Binding Item.Description}" Grid.Column="1"/>
</Grid>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
<code>
This XAML binds the treeview items to the collection of book items and displays the Item subclass's Description and Code, the treeview populates and displays correctly but now I want to sort the treeview on either Item.Code or Item.Description and have tried the following with no results:
<pre>
var bookItemsSort = CollectionViewSource.GetDefaultView(_bookItemList) as ListCollectionView;
tvList.ItemsSource = _bookItemList; //bind the book items to the treeview
bookItemsSort.SortDescriptions.Clear();
bookItemsSort.SortDescriptions.Add(new SortDescription(sort, Ascending));
<code>
I've had this code work correctly for other treeviews so I can only guess it is a problem with binding to a subclass.
While the answers here provided partial answers to my question, none of them gave the answer that I needed.
The most sensible solution for this problem was to write my own object comparer for this object type and sort the underlying list and then re-bind the new list to the treeview. This allowed for comparing sublasses at any nested level which I couldn't make work any other way :)
You need to get the default view for each sub-list, and apply a CollectionViewSource sorting to it. The code you posted only affects the top level items.
Bind your TreeView.ItemsSource to the DefaultView. SortDescriptions will not change your DataList, only the View of it.
tvList.ItemsSource = bookItemsSort;
See Bea Stollnitz blog: How can I sort a hierarchy?