Search Results

Search found 369 results on 15 pages for 'observablecollection'.

Page 6/15 | < Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • How to determine if an item is the last one in a WPF ItemTemplate?

    - by Mike
    Hi everyone, I have some XAML <ItemsControl Name="mItemsControl"> <ItemsControl.ItemTemplate> <DataTemplate> <TextBox Text="{Binding Mode=OneWay}" KeyUp="TextBox_KeyUp"/> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> that's bound to a simple ObservableCollection private ObservableCollection<string> mCollection = new ObservableCollection<string>(); public MainWindow() { InitializeComponent(); this.mCollection.Add("Test1"); this.mCollection.Add("Test2"); this.mItemsControl.ItemsSource = this.mCollection; } Upon hitting the enter key in the last TextBox, I want another TextBox to appear. I have code that does it, but there's a gap: private void TextBox_KeyUp(object sender, KeyEventArgs e) { if (e.Key != Key.Enter) { return; } TextBox textbox = (TextBox)sender; if (IsTextBoxTheLastOneInTheTemplate(textbox)) { this.mCollection.Add("A new textbox appears!"); } } The function IsTextBoxTheLastOneInTheTemplate() is something that I need, but can't figure out how to write. How would I go about writing it? I've considered using ItemsControl.ItemContainerGenerator, but can't put all the pieces together. Thanks! -Mike

    Read the article

  • problem in silverlight 4 async how to wait till result come

    - by AQEEL
    Here is what i have problem i have following code : //Get All master record entryE_QuestMaster = new ObservableCollection<E_QuestMaster>(); QuestVM.getExamsMasterbyExamID(eUtility.ConvertInt32(this.txtID.Text), ref entryE_QuestMaster); // //Loop to show questions int iNumber=1; foreach (var oIn in entryE_QuestMaster) { Node subNode = new Node(); subNode.Content = oIn.e_Question; subNode.Name = "Quest_" + iNumber.ToString().Trim(); subNode.Tag = oIn.e_QID.ToString(); subNode.Icon = "/Images/Number/" + iNumber.ToString().Trim() + ".gif"; iNumber++; this.tvMainNode.Nodes.Add(subNode); } here is async method calling wcf service /// <summary> /// /// </summary> /// <param name="ID"></param> public void getExamsMasterbyExamID(int ID, ref ObservableCollection<E_QuestMaster> iCollectionData) { ObservableCollection<E_QuestMaster> iCollectionDataResult = iCollectionData; eLearningDataServiceClient client = new eLearningDataServiceClient(); client.getExamsMasterCompleted+=(s,e)=> { iCollectionDataResult = e.Result; }; client.getExamsMasterAsync(ID); } problem : when ever system run -- QuestVM.getExamsMasterbyExamID(eUtility.ConvertInt32(this.txtID.Text), ref entryE_QuestMaster); its does not wait till i get e.result its just move to next line of code which is foreach loop. plssss help any one or give idea with sample code what should i do to wait till e.result i wanted to some how wait till i get e.result any idea ?

    Read the article

  • Does WPF break an Entity Framework ObjectContext?

    - by David Veeneman
    I am getting started with Entity Framework 4, and I am getting ready to write a WPF demo app to learn EF4 better. My LINQ queries return IQueryable<T>, and I know I can drop those into an ObservableCollection<T> with the following code: IQueryable<Foo> fooList = from f in Foo orderby f.Title select f; var observableFooList = new ObservableCollection<Foo>(fooList); At that point, I can set the appropriate property on my view model to the observable collection, and I will get WPF data binding between the view and the view model property. Here is my question: Do I break the ObjectContext when I move my foo list to the observable collection? Or put another way, assuming I am otherwise handling my ObjectContext properly, will EF4 properly update the model (and the database)? The reason why I ask is this: NHibernate tracks objects at the collection level. If I move an NHibernate IList<T> to an observable collection, it breaks NHibernate's change tracking mechanism. That means I have to do some very complicated object wrapping to get NHibernate to work with WPF. I am looking at EF4 as a way to dispense with all that. So, to get EF4 working with WPF, is it as simple as dropping my IQueryable<T> results into an ObservableCollection<T>. Does that preserve change-tracking on my EDM entity objects? Thanks for your help.

    Read the article

  • Confusion about WPF binding...

    - by Vladislav
    I am trying to bind a 2D array of buttons arranged in stackpanels to a 2D ObservableCollection... Yet, I'm afraid I don't understand something very elementary about binding. My XAML: <Window.Resources> <DataTemplate x:Key="ItemsAsButtons"> <Button Content="{Binding}" Height="100" Width="100"/> </DataTemplate> <DataTemplate x:Key="PanelOfPanels"> <ItemsControl ItemsSource="{Binding Path=DayNumbers}" ItemTemplate=" {DynamicResource ItemsAsButtons}"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <StackPanel Orientation="Horizontal"/> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> </ItemsControl> </DataTemplate> </Window.Resources> ... <ItemsControl x:Name="DaysPanel" Grid.ColumnSpan="7" Grid.Row="2" ItemTemplate="{DynamicResource PanelOfPanels}"/> My C# code: The backend: /// <summary> /// Window BE for Calendar.xaml /// </summary> public partial class Calendar : Window { private CalendarViewModel _vm; public Calendar() { InitializeComponent(); _vm = new CalendarViewModel(); this.DataContext = _vm; } } The ViewModel: class CalendarViewModel { CalendarMonth _displayedMonth; EventCalendar _calendar; public CalendarViewModel() { _displayedMonth = new CalendarMonth(); } public ObservableCollection<ObservableCollection<int>> DayNumbers { get { return _displayedMonth.DayNumbers; } } } I'm trying to populate the buttons with values from CalendarViewModel.DayNumbers - yet the buttons do not appear. I'm clearly doing something wrong with my binding.

    Read the article

  • Silverlight Data Binding for Collection in Stack Panel

    - by Blake Blackwell
    I'm new to Silverlight, so I don't have a complete grasp of all the controls at my disposal. What I would like to do is use databinding and a view model to maintain a collection of items. Here is some mock code for what I'd like to do: Model public class MyItem { public string DisplayText { get; set; } public bool Enabled { get; set; } } ViewModel public class MyViewModel : INotifyPropertyChanged { private ObservableCollection<MyItem> _myItems = new ObservableCollection<MyItem>(); public ObservableCollection<MyItem> MyItems { get { return _myItems; } set { _myItems = value NotifyPropertyChanged(this, "MyItems"); } } } View <Grid x:Name="LayoutRoot" Background="White"> <StackPanel ItemsSource="{Binding MyItems}"> <StackPanel Orientation="Horizontal"> <CheckBox "{Binding Enabled, Mode=TwoWay}"></CheckBox> <TextBlock Text="{Binding DisplayText, Mode=TwoWay}" /> </StackPanel> </StackPanel> </Grid> So my end goal would be that every time I add another MyItem to the MyItems collection it would create a new StackPanel with checkbox and textblock. I don't have to use a stack panel but just thought I'd use that for this sample.

    Read the article

  • What changed in the DataGrid that means it won't work anymore?

    - by Jeff Yates
    I have a Silverlight app with a DataGrid containing some custom columns and all was working well. Then I updated to Silverlight 3 tools for VS 2008 SP1 and rebuilt it. Now it has the following problems: Rows aren't added when the collection is modified. The ItemsSource property is (and always has been) set to an ObservableCollection instance, which notifies when its contents change. This worked fine for Silverlight 2. However, in Silverlight 3 to get this working at all, I now have to null and then re-set ItemsSource - this seems like I'm hiding a bigger issue but I can't work out what that might be. I cannot select a row or a cell anymore. If I'm lucky, I can select one whole row before it stops working. I can't edit anything. I suspect this is related to the previous point. I'll post some source when I am able, but first I have to strip it down to the bare minimum. In the meantime, I was hoping someone might have some idea of what may be going on here. My gut feeling on the second two points is that my bindings are no longer working, but that's just a guess and if it is the case, I have no idea which ones. Thanks for any help anyone might be able to provide. Update So, I finally reduced my problem down to a simple works/doesn't work comparison. The problem seems to occur if I override Equals in my element type. As soon as I do that, something happens strangely in the ObservableCollection that contains that type, it seems, and my application breaks. To make it more interesting, there is a check to make sure that duplicate items don't even get close to being added to the collection. I don't exactly know why ObservableCollection needs to compare equality when inserting items (the stack trace indicates it is using IndexAt) but this seems to cause the issue. So, any thoughts?

    Read the article

  • How to retrieve data from a dialog box?

    - by Ralph
    Just trying to figure out an easy way to either pass or share some data between the main window and a dialog box. I've got a collection of variables in my main window that I want to pass to a dialog box so that they can be edited. They way I've done it now, is I pass in the list to the constructor of the dialog box: private void Button_Click(object sender, RoutedEventArgs e) { var window = new VariablesWindow(_templateVariables); window.Owner = this; window.ShowDialog(); if(window.DialogResult == true) _templateVariables = new List<Variable>(window.Variables); } And then in there, I guess I need to deep-copy the list, public partial class VariablesWindow : Window { public ObservableCollection<Variable> Variables { get; set; } public VariablesWindow(IEnumerable<Variable> vars) { Variables = new ObservableCollection<Variable>(vars); // ... So that when they're edited, it doesn't get reflected back in the main window until the user actually hits "Save". Is that the correct approach? If so, is there an easy way to deep-copy an ObservableCollection? Because as it stands now, I think my Variables are being modified because it's only doing a shallow-copy.

    Read the article

  • Best practices for using the Entity Framework with WPF DataBinding

    - by Ken Smith
    I'm in the process of building my first real WPF application (i.e., the first intended to be used by someone besides me), and I'm still wrapping my head around the best way to do things in WPF. It's a fairly simple data access application using the still-fairly-new Entity Framework, but I haven't been able to find a lot of guidance online for the best way to use these two technologies (WPF and EF) together. So I thought I'd toss out how I'm approaching it, and see if anyone has any better suggestions. I'm using the Entity Framework with SQL Server 2008. The EF strikes me as both much more complicated than it needs to be, and not yet mature, but Linq-to-SQL is apparently dead, so I might as well use the technology that MS seems to be focusing on. This is a simple application, so I haven't (yet) seen fit to build a separate data layer around it. When I want to get at data, I use fairly simple Linq-to-Entity queries, usually straight from my code-behind, e.g.: var families = from family in entities.Family.Include("Person") orderby family.PrimaryLastName, family.Tag select family; Linq-to-Entity queries return an IOrderedQueryable result, which doesn't automatically reflect changes in the underlying data, e.g., if I add a new record via code to the entity data model, the existence of this new record is not automatically reflected in the various controls referencing the Linq query. Consequently, I'm throwing the results of these queries into an ObservableCollection, to capture underlying data changes: familyOC = new ObservableCollection<Family>(families.ToList()); I then map the ObservableCollection to a CollectionViewSource, so that I can get filtering, sorting, etc., without having to return to the database. familyCVS.Source = familyOC; familyCVS.View.Filter = new Predicate<object>(ApplyFamilyFilter); familyCVS.View.SortDescriptions.Add(new System.ComponentModel.SortDescription("PrimaryLastName", System.ComponentModel.ListSortDirection.Ascending)); familyCVS.View.SortDescriptions.Add(new System.ComponentModel.SortDescription("Tag", System.ComponentModel.ListSortDirection.Ascending)); I then bind the various controls and what-not to that CollectionViewSource: <ListBox DockPanel.Dock="Bottom" Margin="5,5,5,5" Name="familyList" ItemsSource="{Binding Source={StaticResource familyCVS}, Path=., Mode=TwoWay}" IsSynchronizedWithCurrentItem="True" ItemTemplate="{StaticResource familyTemplate}" SelectionChanged="familyList_SelectionChanged" /> When I need to add or delete records/objects, I manually do so from both the entity data model, and the ObservableCollection: private void DeletePerson(Person person) { entities.DeleteObject(person); entities.SaveChanges(); personOC.Remove(person); } I'm generally using StackPanel and DockPanel controls to position elements. Sometimes I'll use a Grid, but it seems hard to maintain: if you want to add a new row to the top of your grid, you have to touch every control directly hosted by the grid to tell it to use a new line. Uggh. (Microsoft has never really seemed to get the DRY concept.) I almost never use the VS WPF designer to add, modify or position controls. The WPF designer that comes with VS is sort of vaguely helpful to see what your form is going to look like, but even then, well, not really, especially if you're using data templates that aren't binding to data that's available at design time. If I need to edit my XAML, I take it like a man and do it manually. Most of my real code is in C# rather than XAML. As I've mentioned elsewhere, entirely aside from the fact that I'm not yet used to "thinking" in it, XAML strikes me as a clunky, ugly language, that also happens to come with poor designer and intellisense support, and that can't be debugged. Uggh. Consequently, whenever I can see clearly how to do something in C# code-behind that I can't easily see how to do in XAML, I do it in C#, with no apologies. There's been plenty written about how it's a good practice to almost never use code-behind in WPF page (say, for event-handling), but so far at least, that makes no sense to me whatsoever. Why should I do something in an ugly, clunky language with god-awful syntax, an astonishingly bad editor, and virtually no type safety, when I can use a nice, clean language like C# that has a world-class editor, near-perfect intellisense, and unparalleled type safety? So that's where I'm at. Any suggestions? Am I missing any big parts of this? Anything that I should really think about doing differently?

    Read the article

  • TwoWay Binding With ItemsControl

    - by Andrew
    I'm trying to write a user control that has an ItemsControl, the ItemsTemplate of which contains a TextBox that will allow for TwoWay binding. However, I must be making a mistake somewhere in my code, because the binding only appears to work as if Mode=OneWay. This is a pretty simplified excerpt from my project, but it still contains the problem: <UserControl x:Class="ItemsControlTest.UserControl1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Height="300" Width="300"> <Grid> <StackPanel> <ItemsControl ItemsSource="{Binding Path=.}" x:Name="myItemsControl"> <ItemsControl.ItemTemplate> <DataTemplate> <TextBox Text="{Binding Mode=TwoWay, UpdateSourceTrigger=LostFocus, Path=.}" /> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> <Button Click="Button_Click" Content="Click Here To Change Focus From ItemsControl" /> </StackPanel> </Grid> </UserControl> Here's the code behind for the above control: using System; using System.Windows; using System.Windows.Controls; using System.Collections.ObjectModel; namespace ItemsControlTest { /// <summary> /// Interaction logic for UserControl1.xaml /// </summary> public partial class UserControl1 : UserControl { public ObservableCollection<string> MyCollection { get { return (ObservableCollection<string>)GetValue(MyCollectionProperty); } set { SetValue(MyCollectionProperty, value); } } // Using a DependencyProperty as the backing store for MyCollection. This enables animation, styling, binding, etc... public static readonly DependencyProperty MyCollectionProperty = DependencyProperty.Register("MyCollection", typeof(ObservableCollection<string>), typeof(UserControl1), new UIPropertyMetadata(new ObservableCollection<string>())); public UserControl1() { for (int i = 0; i < 6; i++) MyCollection.Add("String " + i.ToString()); InitializeComponent(); myItemsControl.DataContext = this.MyCollection; } private void Button_Click(object sender, RoutedEventArgs e) { // Insert a string after the third element of MyCollection MyCollection.Insert(3, "Inserted Item"); // Display contents of MyCollection in a MessageBox string str = ""; foreach (string s in MyCollection) str += s + Environment.NewLine; MessageBox.Show(str); } } } And finally, here's the xaml for the main window: <Window x:Class="ItemsControlTest.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:src="clr-namespace:ItemsControlTest" Title="Window1" Height="300" Width="300"> <Grid> <src:UserControl1 /> </Grid> </Window> Well, that's everything. I'm not sure why editing the TextBox.Text properties in the window does not seem to update the source property for the binding in the code behind, namely MyCollection. Clicking on the button pretty much causes the problem to stare me in the face;) Please help me understand where I'm going wrong. Thanx! Andrew

    Read the article

  • WPF Databinding- Part 2 of 3

    - by Shervin Shakibi
    This is a follow up to my previous post WPF Databinding- Not your fathers databinding Part 1-3 you can download the source code here  http://ssccinc.com/wpfdatabinding.zip Example 04   In this example we demonstrate  the use of default properties and also binding to an instant of an object which is part of a collection bound to its container. this is actually not as complicated as it sounds. First of all, lets take a look at our Employee class notice we have overridden the ToString method, which will return employees First name , last name and employee number in parentheses, public override string ToString()        {            return String.Format("{0} {1} ({2})", FirstName, LastName, EmployeeNumber);        }   in our XAML we have set the itemsource of the list box to just  “Binding” and the Grid that contains it, has its DataContext set to a collection of our Employee objects. DataContext="{StaticResource myEmployeeList}"> ….. <ListBox Name="employeeListBox"  ItemsSource="{Binding }" Grid.Row="0" /> the ToString in the method for each instance will get executed and the following is a result of it. if we did not have a ToString the list box would look  like this: now lets take a look at the grid that will display the details when someone clicks on an Item, the Grid has the following DataContext DataContext="{Binding ElementName=employeeListBox,            Path=SelectedItem}"> Which means its bound to a specific instance of the Employee object. and within the gird we have textboxes that are bound to different Properties of our class. <TextBox Grid.Row="0" Grid.Column="1" Text="{Binding Path=FirstName}" /> <TextBox Grid.Row="1" Grid.Column="1" Text="{Binding Path=LastName}" /> <TextBox Grid.Row="2" Grid.Column="1" Text="{Binding Path=Title}" /> <TextBox Grid.Row="3" Grid.Column="1" Text="{Binding Path=Department}" />   Example 05   This project demonstrates use of the ObservableCollection and INotifyPropertyChanged interface. Lets take a look at Employee.cs first, notice it implements the INotifyPropertyChanged interface now scroll down and notice for each setter there is a call to the OnPropertyChanged method, which basically will will fire up the event notifying to the value of that specific property has been changed. Next EmployeeList.cs notice it is an ObservableCollection . Go ahead and set the start up project to example 05 and then run. Click on Add a new employee and the new employee should appear in the list box.   Example 06   This is a great example of IValueConverter its actuall a two for one deal, like most of my presentation demos I found this by “Binging” ( formerly known as g---ing) unfortunately now I can’t find the original author to give him  the credit he/she deserves. Before we look at the code lets run the app and look at the finished product, put in 0 in Celsius  and you should see Fahrenheit textbox displaying to 32 degrees, I know this is calculating correctly from my elementary school science class , also note the color changed to blue, now put in 100 in Celsius which should give us 212 Fahrenheit but now the color is red indicating it is hot, and finally put in 75 Fahrenheit and you should see 23.88 for Celsius and the color now should be black. Basically IValueConverter allows us different types to be bound, I’m sure you have had problems in the past trying to bind to Date values . First look at FahrenheitToCelciusConverter.cs first notice it implements IValueConverter. IValueConverter has two methods Convert and ConvertBack. In each method we have the code for converting Fahrenheit to Celsius and vice Versa. In our XAML, after we set a reference in our Windows.Resources section. and for txtCelsius we set the path to TxtFahrenheit and the converter to an instance our FahrenheitToCelciusConverter converter. no need to repeat this for TxtFahrenheit since we have a convert and ConvertBack. Text="{Binding  UpdateSourceTrigger=PropertyChanged,            Path=Text,ElementName=txtFahrenheit,            Converter={StaticResource myTemperatureConverter}}" As mentioned earlier this is a twofer Demo, in the second demo, we basically are converting a double datatype to a brush. Lets take a look at TemperatureToColorConverter, notice we in our Covert Method, if the value is less than our cold temperature threshold we return a blue brush and if it is higher than our hot temperature threshold we return a redbrush. since we don’t have to convert a brush to double value in our example the convert back is not being implemented. Take time and go through these three examples and I hope you have a better understanding   of databinding, ObservableCollection  and IValueConverter . Next blog posting we will talk about ValidationRule, DataTemplates and DataTemplate triggers.

    Read the article

  • Local LINQtoSQL Database For Your Windows Phone 7 Application

    - by Tim Murphy
    There aren’t many applications that are of value without having some for of data store.  In Windows Phone development we have a few options.  You can store text directly to isolated storage.  You can also use a number of third party libraries to create or mimic databases in isolated storage.  With Mango we gained the ability to have a native .NET database approach which uses LINQ to SQL.  In this article I will try to bring together the components needed to implement this last type of data store and fill in some of the blanks that I think other articles have left out. Defining A Database The first things you are going to need to do is define classes that represent your tables and a data context class that is used as the overall database definition.  The table class consists of column definitions as you would expect.  They can have relationships and constraints as with any relational DBMS.  Below is an example of a table definition. First you will need to add some assembly references to the code file. using System.ComponentModel;using System.Data.Linq;using System.Data.Linq.Mapping; You can then add the table class and its associated columns.  It needs to implement INotifyPropertyChanged and INotifyPropertyChanging.  Each level of the class needs to be decorated with the attribute appropriate for that part of the definition.  Where the class represents the table the properties represent the columns.  In this example you will see that the column is marked as a primary key and not nullable with a an auto generated value. You will also notice that the in the column property’s set method It uses the NotifyPropertyChanging and NotifyPropertyChanged methods in order to make sure that the proper events are fired. [Table]public class MyTable: INotifyPropertyChanged, INotifyPropertyChanging{ public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(string propertyName) { if(PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } public event PropertyChangingEventHandler PropertyChanging; private void NotifyPropertyChanging(string propertyName) { if(PropertyChanging != null) { PropertyChanging(this, new PropertyChangingEventArgs(propertyName)); } } private int _TableKey; [Column(IsPrimaryKey = true, IsDbGenerated = true, DbType = "INT NOT NULL Identity", CanBeNull = false, AutoSync = AutoSync.OnInsert)] public int TableKey { get { return _TableKey; } set { NotifyPropertyChanging("TableKey"); _TableKey = value; NotifyPropertyChanged("TableKey"); } } The last part of the database definition that needs to be created is the data context.  This is a simple class that takes an isolated storage location connection string its constructor and then instantiates tables as public properties. public class MyDataContext: DataContext{ public MyDataContext(string connectionString): base(connectionString) { MyRecords = this.GetTable<MyTable>(); } public Table<MyTable> MyRecords;} Creating A New Database Instance Now that we have a database definition it is time to create an instance of the data context within our Windows Phone app.  When your app fires up it should check if the database already exists and create an instance if it does not.  I would suggest that this be part of the constructor of your ViewModel. db = new MyDataContext(connectionString);if(!db.DatabaseExists()){ db.CreateDatabase();} The next thing you have to know is how the connection string for isolated storage should be constructed.  The main sticking point I have found is that the database cannot be created unless the file mode is read/write.  You may have different connection strings but the initial one needs to be similar to the following. string connString = "Data Source = 'isostore:/MyApp.sdf'; File Mode = read write"; Using you database Now that you have done all the up front work it is time to put the database to use.  To make your life a little easier and keep proper separation between your view and your viewmodel you should add a couple of methods to the viewmodel.  These will do the CRUD work of your application.  What you will notice is that the SubmitChanges method is the secret sauce in all of the methods that change data. private myDataContext myDb;private ObservableCollection<MyTable> _viewRecords;public ObservableCollection<MyTable> ViewRecords{ get { return _viewRecords; } set { _viewRecords = value; NotifyPropertyChanged("ViewRecords"); }}public void LoadMedstarDbData(){ var tempItems = from MyTable myRecord in myDb.LocalScans select myRecord; ViewRecords = new ObservableCollection<MyTable>(tempItems);}public void SaveChangesToDb(){ myDb.SubmitChanges();}public void AddMyTableItem(MyTable newScan){ myDb.LocalScans.InsertOnSubmit(newScan); myDb.SubmitChanges();}public void DeleteMyTableItem(MyTable newScan){ myDb.LocalScans.DeleteOnSubmit(newScan); myDb.SubmitChanges();} Updating existing database What happens when you need to change the structure of your database?  Unfortunately you have to add code to your application that checks the version of the database which over time will create some pollution in your codes base.  On the other hand it does give you control of the update.  In this example you will see the DatabaseSchemaUpdater in action.  Assuming we added a “Notes” field to the MyTable structure, the following code will check if the database is the latest version and add the field if it isn’t. if(!myDb.DatabaseExists()){ myDb.CreateDatabase();}else{ DatabaseSchemaUpdater dbUdater = myDb.CreateDatabaseSchemaUpdater(); if(dbUdater.DatabaseSchemaVersion < 2) { dbUdater.AddColumn<MyTable>("Notes"); dbUdater.DatabaseSchemaVersion = 2; dbUdater.Execute(); }} Summary This approach does take a fairly large amount of work, but I think the end product is robust and very native for .NET developers.  It turns out to be worth the investment. del.icio.us Tags: Windows Phone,Windows Phone 7,LINQ to SQL,LINQ,Database,Isolated Storage

    Read the article

  • Silverlight child windows in MVVM pattern

    - by rrejc
    Hello, I am trying to find the right way to get the data from a ChildWindow/popup using a MVVM pattern in Silverlight (3). For example: I have a main page with a data entry form and I want to open a popup with a list of customers. When user selects a customer I want to transfer selected customer into the main page. This is what the (example) code which I am using at the moment: Main page public partial class MainPage : UserControl { public MainPageViewModel ViewModel { get; private set; } public MainPage() { InitializeComponent(); ViewModel = new MainPageViewModel(); DataContext = ViewModel; } private void SearchCustomer_Click(object sender, RoutedEventArgs e) { ViewModel.SearchCustomer(); } } public class MainPageViewModel: ViewModel { private string customer; public string Customer { get { return customer; } set { customer = value; RaisePropertyChanged("Customer"); } } public void SearchCustomer() { // Called from a view SearchWindow searchWindow = new SearchWindow(); searchWindow.Closed += (sender, e) => { if ((bool)searchWindow.DialogResult) { Customer = searchWindow.ViewModel.SelectedCustomer.ToString(); } }; searchWindow.Show(); } } Child window public partial class SearchWindow : ChildWindow { public SearchWindowViewModel ViewModel { get; private set; } public SearchWindow() { InitializeComponent(); ViewModel = new SearchWindowViewModel(); DataContext = ViewModel; } private void OKButton_Click(object sender, RoutedEventArgs e) { DialogResult = ViewModel.OkButtonClick(); } private void CancelButton_Click(object sender, RoutedEventArgs e) { DialogResult = ViewModel.CancelButtonClick(); } } public class SearchWindowViewModel: ViewModel { private Customer selectedCustomer; private ObservableCollection<Customer> customers; public ObservableCollection<Customer> Customers { get { return customers; } set {customers = value; RaisePropertyChanged("Customers"); } } public Customer SelectedCustomer { get { return selectedCustomer; } set { selectedCustomer = value; RaisePropertyChanged("SelectedCustomer"); } } public SearchWindowViewModel() { Customers = new ObservableCollection<Customer>(); ISearchService searchService = new FakeSearchService(); foreach (Customer customer in searchService.FindCustomers("dummy")) Customers.Add(customer); } public bool? OkButtonClick() { if (SelectedCustomer != null) return true; else return null; // show some error message before that } public bool? CancelButtonClick() { return false; } } Is this the right way or is there anything more "simple"? Cheers, Rok

    Read the article

  • ItemsControl.ItemsSource MVVM performance

    - by bitbonk
    I have an (non-virtualized) ItemsControl that binds its ItemsSource to a ObeservableCollection of ViewModel instances. Now once the large amount Model instances is loaded all the ViewModel complemnents needs to be added to that ObservableCollection. How can I add a large amount of ViewModels without making the UI Thread hang? I suppose the UI Thread hangs because each time a new item is added the ItemsControl needs to update itself and does layout etc. over and over again. Should I suspend the binding add all items and then resume? If so, how? Should I override the ObservableCollection to implement an AddRange so only 1 CollectionChanged Event is fired for adding multiple items? Or alternatively just replace the whole collection? Or is it better to add each items separately and call Dispatcher.Invoke for each item separately? So I would unblock frequently. How do you handle large dynamic lists that can not be virtualized?

    Read the article

  • Wpf datagrid row not updating when binded collection updated?

    - by RAJ K
    I have product class class Products { public int ProductID { get; set; } public int Quantity { get; set; } public string Description { get; set; } public decimal Price { get; set; } public decimal SubTotal { get; set; } } public List<Products> ProductsList = new List<Products>(); I have binded this "ProductList" to wpf datagrid. This datagrid shows item already in collection (before DataGrid.DataContext applied) but not showing new item added. I am using List< instead of ObservableCollection< because I want to update items if user changes quantity. I don't know how to do that using ObservableCollection<. Some code will help thanks

    Read the article

  • ItemsControl.ItemsSource MVVM perormance

    - by bitbonk
    I have an (non-virtualized) ItemsControl that binds its ItemsSource to a ObeservableCollection of ViewModel instances. Now once the large amount Model instances is loaded all the ViewModel complemnents needs to be added to that ObservableCollection. How can I add a large amount of ViewModels without making the UI Thread hang? I suppose the UI Thread hangs because each time a new item is added the ItemsControl needs to update itself and does layout etc. over and over again. Should I suspend the binding add all items and then resume? If so, how? Should I override the ObservableCollection to implement an AddRange so only 1 CollectionChanged Event is fired for adding multiple items? Or alternatively just replace the whole collection? Or is it better to add each items separately and call Dispatcher.Invoke for each item separately? So I would unblock frequently. How do you handle large dynamic lists that can not be virtualized?

    Read the article

  • Diagramming in Silverlight MVVM- connecting shapes

    - by silverfighter
    Hi, have I have a quesition regarding MVVM pattern in the uses case of diagramming. What I have so far is a list of Items which are my Shapes. ObservableCollection<ItemsViewModels> Items; and a Collection of Connection of Items ObservableCollection<ConnectionViewModel> Each ItemViewModel has an ID and a ConnectionViewModel has two ID to connect the Items. My ItemsViewModel Collection is bound to a itemscontrol which is layout on a Canvas. With the ElementMouseDragBehavior I am able to drag my Items around. Now comes my big question =) How can I visualize my connections that I will be able to move the items around and the items stay connected with a line either straign or bezier. I don't know how to abstract that with the mvvm pattern. Thanks for any help...

    Read the article

  • WPF/MVVM: How can I use several CollectionView`s for aggregated entities ?

    - by msfanboy
    Hello, I have a Customer with Orders and those have products. Everything aggregated with collections of type ObservableCollection. All 3 collections are bound to a datagrid/combobox. I can only make the root collection (ObservableCollection Customers{ get;set;} ) passing to a CollectionView so I can move the current customer within the combobox. But how can I move around the current Order in the datagrid? How to pass the selected Orders to another CollectionView ? Does all this maybe not work?

    Read the article

  • MVVM: how to set the datacontext of a user control

    - by EVA
    Hi, I'm writing an application in WPF, using the MVVm toolkit and have problems with hooking up the viewmodel and view. The model is created with ado.net entity framework. The viewmodel: public class CustomerViewModel { private Models.Customer customer; //constructor private ObservableCollection<Models.Customer> _customer = new ObservableCollection<Models.Customer>(); public ObservableCollection<Models.Customer> AllCustomers { get { return _customer; } } private Models.Customer _selectedItem; public Models.Customer SelectedItem { get { return _selectedItem; } } public void LoadCustomers() { List<Models.Customer> list = DataAccessLayer.getcustomers(); foreach (Models.Customer customer in list) { this._customer.Add(customer); } } } And the view (no code behind at the moment): <UserControl x:Class="Customers.Customer" 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" mc:Ignorable="d" xmlns:vm ="clr-namespace:Customers.ViewModels" d:DesignHeight="300" d:DesignWidth="300" xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit" > <Grid> <toolkit:DataGrid ItemsSource="{Binding AllCustomers}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}" AutoGenerateColumns="True"> </toolkit:DataGrid> <toolkit:DataGrid ItemsSource="{Binding SelectedItem.Orders}"> </toolkit:DataGrid> </Grid> </UserControl> And dataaccesslayer class: class DataAccessLayer { public List<Customer> customers = new List<Customer>(); public static List<Customer> getcustomers() { entities db = new entities(); var customers = from c in db.Customer.Include("Orders") select c; return customers.ToList(); } } The problem is that no data is displayed simply because the data context is not set. I tried to do it in a code-behind but is did not work. I would prefer to do it in a xaml file anyway. Another problem is with the SelectedItem binding - the code is never used. Thanks for help! Regards, EV.

    Read the article

  • DataTemplate in ListBox

    - by Anu
    Hi, I have tabcontrol,in that by pressing second tab button im adding data to third Tab Listbox.But its not get added. SecondTab function: private void Callbutton_Click(object sender, RoutedEventArgs e) { tab.AddPresetmenu("CALL BUTTON"); } ThirdTab Fucntion: ObservableCollection<DataItem> items = new ObservableCollection<DataItem>(); public void AddPresetmenu(string pMenu) { items.Add(new DataItem(pMenu)); menubox.ItemsSource = items; } Third Tab ListBox XAML: <ListBox x:Name="menubox" Margin="0,5,0,0" Height="244" Width="240" Background="Silver" BorderThickness="0"> </ListBox> I think Im missing something.Please Help me.

    Read the article

  • ListBox item doesn't get refresh in WPF?

    - by sanjeev40084
    I have a listbox which has couple of items. When double clicked on each item, the user get option to edit item (text of item). Now once i update the item, my item in listbox doesn't get updated. The first window (one which has listbox) is in MainWindow.xaml file and second window is in EditTaskView.xaml(one which let's edit the items text) file. The code that displays items in lists is: Main.Windows.cs public static ObservableCollection TaskList; public void GetTask() { TaskList = new ObservableCollection<Task> { new Task("Task1"), new Task("Task2"), new Task("Task3"), new Task("Task4") }; lstBxTask.ItemsSource = TaskList; } private void lstBxTask_MouseDoubleClick(object sender, MouseButtonEventArgs e) { var selectedTask = (Task)lstBxTask.SelectedItem; EditTask.txtBxEditedText.Text = selectedTask.Taskname; EditTask.PreviousTaskText = selectedTask.Taskname; EditTask.Visibility = Visibility.Visible; } The xaml code that displays the list: <ListBox x:Name="lstBxTask" Style="{StaticResource ListBoxItems}" MouseDoubleClick="lstBxTask_MouseDoubleClick"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <Rectangle Style="{StaticResource LineBetweenListBox}"/> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding Taskname}" Style="{StaticResource TextInListBox}"/> <Button Name="btnDelete" Style="{StaticResource DeleteButton}" Click="btnDelete_Click"/> </StackPanel> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> <ToDoTask:EditTaskView x:Name="EditTask" Grid.Row="1" Grid.RowSpan="2" Grid.ColumnSpan="2" Visibility="Collapsed"/> The Save button in TaskEditView.xaml does this: public string PreviousTaskText { get; set; } private void btnSaveEditedText_Click(object sender, RoutedEventArgs e) { foreach (var t in MainWindow.TaskList) { if (t.Taskname == PreviousTaskText) { t.Taskname = txtBxEditedText.Text; } } Visibility = Visibility.Collapsed; } TaskList is the ObservableCollection, and i though once you update the value the UI gets refreshed. But doesn't seem to work that way. What am i missing?

    Read the article

  • adding child nodes to a treeview control in wpf,c#

    - by ebhakt
    Hi , i have implemented a treeview control on a buttonclick event like this: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Collections.ObjectModel; namespace TaxonomyTreeview { /// /// Interaction logic for Window1.xaml /// public partial class Window1 : Window { ObservableCollection _TaxonomyCollection = new ObservableCollection(); public Window1() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { } public ObservableCollection<TaxonomyData> TaxonomyCollection { get { return _TaxonomyCollection; } } private void SelectedTaxonomyChanged(object sender, RoutedPropertyChangedEventArgs<Object> e) { TaxonomyData taxo = taxonomytree.SelectedItem as TaxonomyData; if (taxo != null) { MessageBox.Show("" + taxo.Tid); } } public class TaxonomyData { private string _name; private string _tid; public string Tid { get { return _tid; } set { _tid = value; } } public string Name { get { return _name; } set { _name = value; } } public TaxonomyData(string name, string tid) { Name = name; Tid = tid; } } private void populate_Click(object sender, RoutedEventArgs e) { taxonomytree.Items.Clear(); TaxonomyCollection.Add(new TaxonomyData("Taxonomy1", "1")); taxonomytree.Items.Add(TaxonomyCollection[0]); } } } The xaml code is : <TextBox Height="23" Margin="20,9,0,0" Name="startvid" VerticalAlignment="Top" HorizontalAlignment="Left" Width="120" /> <TextBox Height="23" Margin="165,9,151,0" Name="endvid" VerticalAlignment="Top" /> <Button Height="23.78" HorizontalAlignment="Right" Margin="0,8.22,11,0" Name="populate" VerticalAlignment="Top" Width="115" Click="populate_Click">Populate</Button> <TreeView HorizontalAlignment="Left" Margin="20,53,0,144" Width="120" Name="taxonomytree" ItemsSource="{Binding Window1.TaxonomyCollection}" SelectedItemChanged="SelectedTaxonomyChanged"> <TreeView.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Path=Name}" /> </DataTemplate> </TreeView.ItemTemplate> </TreeView> </Grid> As i want to display, the structure in a hierarchy , i want to know what is the best method to add a child node to this Please help

    Read the article

  • How can I run code in a C# class definition each time any instance of the class is deserialized?

    - by Ben
    I am trying to derive a class from ObservableCollection and I need to run just a single line of code each and every time any instance of this class is deserialized. My thought was to do this: [Serializable] public class ObservableCollection2<T> : ObservableCollection<T>, ISerializable { public ObservableCollection2() : base() { } public ObservableCollection2(SerializationInfo info, StreamingContext context) : base(info, context) { // Put additional code here. } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); } } But I don't have access to those base methods related to serialization. Am I forced to re-write all of the serialization manually?

    Read the article

  • Binding a combobox in XAML to a childwindow property

    - by AlexB
    Hi, I want to display a child window that contains a combobox with several values coming from one of the child window's property: public partial class MyChildWindow : ChildWindow { private ObservableCollection<MyClass> _collectionToBind = // initialize and add items to collection to make sure it s not empty... public ObservableCollection<MyClass> CollectionToBind { get { return _collectionToBind; } set { _collectionToBind = value; } } } How do I bind in XAML my combobox to the ComboBoxContent collection (both are in the same class)? I've tried several things such as: <ComboBox x:Name="linkCombo" ItemsSource="{Binding Path=CollectionToBind }" DisplayMemberPath="Description"> I've only been able to bind it in the code behind file and would like to learn the XAML way to do it. Thank you!

    Read the article

  • lambda expression for a query on two tables that returns records from one table

    - by peetee
    I have two tables TableA (articles) int id int Type string name and TableB (compatibles) int linked_ID int tableA_ID TableA records: id=1, Type=0, name="ArticleA" id=2, Type=1, name="ArticleB" id=3, Type=2, name="ArticleC" id=4, Type=1, name="ArticleD" TableB records: linked_ID= 1, tableA_ID=2 linked_ID= 1, tableA_ID=3 linked_ID= 1, tableA_ID=4 TableB has a list of arcicels that are compatible to a certain article. I am quite new to queries (didn't need them in my projects yet). But as C# and WPF allow some pretty cool automation with Binding I would like to add a binding that returns the following: Give me all articles that are of Type 1 and compatible to my selected article (id=1). The simple part of it works well (articles has a list of all articles): private ObservableCollection<Article> _articles = new ObservableCollection<Article>(); [fill it with the available articles] and then: comboBoxArticles.ItemsSource = _articles.AsBindable().Where( c => c.Typ == 0 ); How can I extend the Where clause to query another table? Thanks a lot in advance.

    Read the article

  • WPF data templates

    - by imekon
    I'm getting started with WPF and trying to get my head around connecting data to the UI. I've managed to connect to a class without any issues, but what I really want to do is connect to a property of the main window. Here's the XAML: <Window x:Class="test3.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:custom="clr-namespace:test3" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <CollectionViewSource Source="{Binding Source={x:Static Application.Current}, Path=Platforms}" x:Key="platforms"/> <DataTemplate DataType="{x:Type custom:Platform}"> <StackPanel> <CheckBox IsChecked="{Binding Path=Selected}"/> <TextBlock Text="{Binding Path=Name}"/> </StackPanel> </DataTemplate> </Window.Resources> <Grid> <ListBox ItemsSource="{Binding Source={StaticResource platforms}}"/> </Grid> Here's the code for the main window: public partial class MainWindow : Window { ObservableCollection<Platform> m_platforms; public MainWindow() { m_platforms = new ObservableCollection<Platform>(); m_platforms.Add(new Platform("PC")); InitializeComponent(); } public ObservableCollection<Platform> Platforms { get { return m_platforms; } set { m_platforms = value; } } } Here's the Platform class: public class Platform { private string m_name; private bool m_selected; public Platform(string name) { m_name = name; m_selected = false; } public string Name { get { return m_name; } set { m_name = value; } } public bool Selected { get { return m_selected; } set { m_selected = value; } } } This all compiles and runs fine but the list box displays with nothing in it. If I put a breakpoint on the get method of Platforms, it doesn't get called. I don't understand as Platforms is what the XAML should be connecting to!

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >