w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Casting specific observablecollection to a generic observablecollection
You can't use ObservableCollection<T> as if it were both covariant and contravariant in T. That's pretty meaningless. Maybe you want to copy the collections (but that may be expensive!): public abstract HeadOffice<T> : IOffice where T : Employee { ObservableCollection<T> _employees = new ObservableCollection<T>(); public ObservableCollection<Employee> Employees { get { return new ObservableCollection<Employee>(_employees); } set { _employees.Clear(); foreach (var e in value) { var t = e as T; if (t == null) throw new InvalidOperationException("..."); _empl

Categories : C#

Can i use LINQ to populate an ObservableCollection of ObservableCollection
I'm not completely sure where child4 is coming from but based on your above structure this will get you Child3. var child3 = observableOfClassA .SelectMany(a => a.classBItems) // flattens list to all classBItems .SelectMany(b => b.classBSubItems) // flattens list to classBItems.classBSubItems .Where(bSub => bSub.name == "child3s Name goes here") // replace with your where clause .FirstOrDefault();

Categories : C#

Replace Entire ObservableCollection with another ObservableCollection
You have some options: Implement INotifyPropertyChanged so you can inform the UI that the value of Items has changed. This does not utilize the fact that INotifyCollectionChanged is implemented on ObservableCollection. It will work, but it defeats the purpose of using an ObservableCollection in the first place. This is not recommended but it works. Related Reading Example Use the ObservableCollection's Add/Remove/Modify/Update methods to modify it in conjunction with the Dispatcher. Note: without the Dispatcher, you will get a NotSupportedException because CollectionViews do not support changes to their SourceCollection from a thread different from the Dispatcher thread. Use the ObservableCollection's Add/Remove/Modify/Update methods to modify it in conjunction with BindingOperati

Categories : C#

ObservableCollection not updating the UI
If the properties are being changed on your Station objects, you need to implement INotifyPropertyChanged on it, and fire the PropertyChanged event in your property setters. It seems like the chart object isn't being notified when your other thread changes the properties. The ObservableCollection will only cause an update in the chart when Station objects are added or removed, not when their properties change. You say that when you hover over the chart you see the updated values, but this may be because the chart is actually calling the getter on the property to display that, so you will see the updated value there (but I'm speculating on this).

Categories : C#

ObservableCollection and DisplayMemberBinding
Since you bind ItemsSource to ObservableCollection<Point> it means that each item is of a Point type which has ValueX and ValueY declared as fields which are not valid binding source. Change them to properties: public double ValueX { get; private set; } public double ValueY { get; private set; } Besides you use Mode=TwoWay for something that is read only. This should be changed to OneWay. If you want to leave TwoWay binding then remove private from the setter but then also you'll need to change GridViewColumn.CellTemplate to be some TextBox instead of using DisplayMemberBinding which is for display only.

Categories : Wpf

Is there a way to sort an Observablecollection?
'OrderregelsGegroepeerd = New ObservableCollection(Of clsOrderItems)(l) Dim NewIndex As Integer = 0 For Each regel As clsOrderItems In l Dim idx As Integer = OrderregelsGegroepeerd.IndexOf(regel) OrderregelsGegroepeerd.Move(idx, NewIndex) NewIndex = NewIndex + 1 Next So that's the way i come up with, now i just have a small problem with the converter behind the new item but thats not a big deal! Thanks for the reply from keyboardP, that i actually only saw it before i figured the problem, but is still a good source of infomation.

Categories : Vb.Net

How to serialize ObservableCollection in C#?
ObservableCollection<T> implements IEnumerable<T> so you should be able to convert it to a List<T> or T[] simply enough with the ToList()/ToArray() extensions. Both of which can be serialized with the DataContractSerializer without issue (as long as the attributes a properly applied).

Categories : C#

How to mock ObservableCollection
I don't think you should mock such base types as List, ObservableCollection, or DateTime (even if it was possible). They are reliable and unlikely to change. Simply use ObservableCollection in your test instead of trying to re-implement it's count-increasing functionality. You always can do state-based verification: var items = new ObservableCollection<int>(); // Do stuff Assert.That(items.Count, Is.EqualTo(5)); If you are using your custom type Foo which is inherited from ObservableCollection<Int32> then you can also implement some IFoo interface which will be easy to mock: public class Foo : ObservableCollection<Int32>, IFoo

Categories : C#

Binding an ObservableCollection to a DataGrid
Set the properties you want databound to public public string FileName { get { return fileName; } set { fileName = value; OnPropertyChanged("FileName"); } } public string Path { get; set; } public string Extension { get; set; }

Categories : C#

Combine List and ObservableCollection
The simple answer to your question is 'yes, but with some work'. The ObservableCollection<T> class extends the Collection<T> class, which implements the IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable interfaces - the same as the List<T> class. However, the ObservableCollection<T> class also implements the INotifyCollectionChanged and INotifyPropertyChanged interfaces, so these are the main difference between the two. Therefore you could extend the List<T> class and manually implement the INotifyCollectionChanged and INotifyPropertyChanged interfaces yourself to get the best of both worlds. Having said that, after manually adding AddRange and Sort methods to my custom ObservableCollection<T> base class, I ha

Categories : C#

add data item to observablecollection?
You need to change ActorsObject objkt = itemGridView.SelectedItem; to ActorsObject objkt = (ActorsObject)itemGridView.SelectedItem; you are missing a cast there.

Categories : C#

how to bind a wpf table to an observablecollection?
The FlowDocument control does not support DataBinding as explained here While there are many great features in flow documents, if your documents are generated from dynamic data, you have a bit of a problem: there is no support for data binding in flow documents. The flow document elements (Section, Table, Run, Paragraph and the like) are dependency objects, but don't define any dependency properties that would allow you to dynamically change or generate content. There is a work around given at the above link, which might be helpful for you.

Categories : C#

Using an object from an ObservableCollection as a property
This will create a new reference to the same object if the types in question are classes and not structs. This is not generally an expensive operation and will not create new objects. So from what you have said I think it is ok.

Categories : C#

mvvm observablecollection and binding
In the Xaml file of your user control named TableControl, add DataContext={Binding} in the root element and I think it should then work (if it's not present). It could also be not working if you have DataContext set inside the code behind of your user control's (e.g.TableControl.xaml.cs) file to something like this.DataContext = this; which makes user control not use the DataContext of Tables collection. You can use this SO Answer to check what exactly is in the DataContext of your user control TableControl. Edit: Try below also, because as per your comment, DataContext for TableControl is conflicting: <DataTemplate> <controls:TableControl DataContext="{Binding}" TableNumber="{Binding Id}" North="{Binding North}" East="{Binding Eas

Categories : C#

Observablecollection not updating in Win Store App
I assume that the problem is regarding the Server property and not the ObservableCollection (I hope I was right ;) ) Does Wall_Post implement the INotifyPropertyChanged? Wall_Post should implement it and the Server property should be something like this: public string Server { get { return this._server; } set { if (this._server != value) { this._server = value; if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs("Server")); } } } }

Categories : C#

Populating a ListBox (WPF) with an ObservableCollection
You need to remove the DisplayMemberPath specifier. This is saying to look for the List1 property on each item of List1. Since List1 merely contains a set of strings, there is no List1 property on System.String, so you get a binding error.

Categories : C#

How can I do CanDelete validation on ObservableCollection?
You shouldn't delete row directly in the Grid, UI is not responsible for performing Business Actions, this should be performed by ViewModel and before that ViewModel should do validation. AllowDelete="False" in DataGrid: <DataGrid.InputBindings> <KeyBinding Key="Delete" Command="{Binding DeleteOrderCommand}" /> </DataGrid.InputBindings> On View Model you will have DeleteOrderCommand. If you replace this View with some other technology and new Control does not have delete row option you would use button. So you could still reuse your ViewModel as button would bind to the DeleteOrderCommand or to the method that this command is calling, as well your validation is in ViewModel so it hasn't disappeared when you switched to View in new technology. UPDATE: You can u

Categories : C#

ObservableCollection don't modify view
Once you are changing record after that your property is not Notifying.so please Notify after changing the collection. Add below line in RefreshGridSource method after collection changed . RaisePropertyChanged("GridItems");

Categories : Wpf

How to check for the duplicates in an ObservableCollection?
Create a new AddressComparer class implementing IEqualityComparer interface Now you use Contains method if(Addresses.Contains(Address,new AddressComparer())) { //your code }

Categories : C#

How to cast a List to an ObservableCollection in wpf?
you can do it by using extension method public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> coll) { var c = new ObservableCollection<T>(); foreach (var e in coll) c.Add(e); return c; } or you can use this constructor The elements are copied onto the ObservableCollection in the same order they are read by the enumerator of the list. ObservableCollection<YourObject> collection = new ObservableCollection<YourObject>(yourList);

Categories : C#

Get single record from observablecollection
listbox.datasource = list.select( x => x ).where( x.id == id); Hope it helps. I suggest maybe using a CollectionView that you bind to the listbox, and filter the list using the code above, and the listbox updates itself.

Categories : C#

How to convert DbSet to ObservableCollection
Don't do this in a converter. Do it in the ViewModel. That way, your ViewModel will have a strongly typed reference to the DbSet<T> (not just an object) and will know what type T is.

Categories : C#

How to convert Querytable to ObservableCollection
You are not initizalizing the PersonList, so PersonList is null. That's why you are getting NullReferenceException, Object reference not set to an instance of an object. public async Task<bool> GetPersons() { try { var dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.db3"); //Initialize the PersonList, so PersonList won't be null. PersonList = new PersonCollection(); using (var db = new SQLite.SQLiteConnection(dbPath)) { var listadepersonas = from x in db.Table<Person>() select x; foreach (var persona in listadepersonas) { PersonList.Add(new Person() { id = persona.id, Name = persona.Last

Categories : C#

How to bind to one element of an ObservableCollection
Usually, especially if you use MVVM, you'll have a viewModel with your ObservableCollection and a property for the SelectedItem that you update with data binding. For example, your viewModel could look like this: class ProductsViewModel : INotifyPropertyChanged { public ObservableCollection<Product> Products { get; set; } private Product _selectedProduct; public Product SelectedProduct { get { return _selectedProduct; } set { _selectedProduct = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("SelectedProduct")); } } public ProductsViewModel() { Products = new ObservableCollection<Product>(); Products.Add(new Prod

Categories : C#

I can't register event CollectionChanged of ObservableCollection
You should avoid having a set property accessor for collection types, one reason being the one you experienced here with events. Another problem is if someone caches the collection and adds items to it later. var old = obj.DeviceAdjustedConfigurations; obj.DeviceAdjustedConfigurations = new ObservableCollection<OfferedConfiguration>(); old.Add(new OfferedConfiguration()); // what should happen here? instead, remove the set-accessor and use the existing collection directly. obj.DeviceAdjustedConfigurations.Add(new OfferedConfiguration()); If you really need to set the collection, you need to handle this with for instance a property change event from the class that owns the DeviceAdjustedConfigurations. public class Item { public static ObservableCollection<OfferedConfi

Categories : C#

RxUI fill ObservableCollection async
Give this a go: public MainWindow() { InitializeComponent(); MaxRows = 100; Translations = new ReactiveCollection<string>(); LoadDataCommand = new ReactiveAsyncCommand(); LoadDataCommand.RegisterAsyncFunction(_ => LoadData()) .Subscribe(items => { foreach(var i in items) Translations.Add(i); }) LoadDataCommand.ThrownExceptions.Subscribe(ex => { Console.WriteLine("Oh crap: {0}", ex); }) InitializeComponent(); this.DataContext = this; } private List<int> LoadData() { // TODO: Return the list of stuff you want to add return Enumerable.Range(0, maxRows).ToList(); } The idea is, LoadData is going to be called on the background thread, you can do whatever you want there, bl

Categories : C#

Again, ObservableCollection doesnt Update item
First option is try to get your auto-generated class to implement INPC if you can. Have a look at Fody.PropertyChanged If that's not possible, since it does have it's properties as "virtual", we can over-ride them in a derived class such as public class ObservablePerson : Person, INotifyPropertyChanged { public override int PersonId { get { return base.PersonId; } set { base.PersonId = value; OnPropertyChanged(); } } public override string PersonName { get { return base.PersonName; } set { base.PersonName = value; OnPropertyChanged(); } } public override int? PersonAge { get { return base.PersonAge; } set { base.PersonAge = value; OnPropertyChanged(); } } public event Pr

Categories : Wpf

ObservableCollection with binding in c# Windows Phone
As I mentioned in your original question, there is a great article that you should go through as an intro to data binding.

Categories : C#

ObservableCollection DataSerialize not serializing
BitmapImage is simply not serializable using data contract and there is no way to change this by yourself. The only way to persist a BitmapImage (it's an image) is to use BinaryWriter or WriteableBitmap. An image converter for tranforming BitmapImage to byte[] and vice-versa will help too.

Categories : C#

How to Bind an Image from an ObservableCollection to View
Your binding needs to point to the correct property in the Picture class which is Source in your case. Try this Xaml <Image x:Name="photo" Grid.Row="0" Source="{Binding Source}" Margin="12" HorizontalAlignment="Center" VerticalAlignment="Center" toolkit:TiltEffect.IsTiltEnabled="True"/>

Categories : C#

Collection that inherits from ObservableCollection - What are the benefits?
One major benefit is that you can define the Add function, which makes inline initialization easier. So for example this: class MyCollection : ObservableCollection<MyObject> { public void Add(string prop1, string prop2) { base.Add(new MyObject { Prop1 = prop1, Prop2 = prop2 }); } } Lets you write this: MyCollection collection = new MyCollection { { "prop1", "prop2" }, { "prop1", "prop2" }, }; A second (related) benefit: if you're working with XAML, having a subclassed collection lets you define collection instances (for design/test cases) as markup, as in: <local:MyCollection xmlns:local="MyNamespace"> <local:MyObject Prop1="prop1" Prop2="prop2" /> <local:MyObject Prop1="prop1" Prop2="prop2" /> </local> Lastly,

Categories : C#

Entity Framework Database first with ObservableCollection
Changing List to ObservableCollection is very easy but if you want to make everything connected and working together you need an architecture and you have to apply some desgin pattern in your application architecture. Very good way to do that is MVVM check it out. code examples: // I recommend you to use see the prism http://compositewpf.codeplex.com/ http://vherp.codeplex.com/

Categories : C#

WPF ObservableCollection and Listbox.itemsource exception
I'm not sure that I understand exactly what you are doing, but here are a couple of suggestions. Have a single ObservableCollection Bind your itemcollection (or listbox, or whatever) to this Depending on the user, clear and fill that observablecollection with list data Have the background worker update the list and refresh the observable collection if anything has changed. Ideally your EmployeeData class will implement the INotifyPropertyChanged interface, so that property changes will get automatically updated in your view.

Categories : Wpf

Is INotifyPropertyChanged needed for binding ObservableCollection?
If the myFiles property can change, then yes, you should raise the PropertyChanged event. If not (that is, if it's got no setter, or it has a private setter that is only set once, e.g. in the constructor), then you don't need to raise the event. The collection itself will raise its own PropertyChanged and CollectionChanged events, but the object that contains the collection must raise PropertyChanged if the property that contains the collection changes.

Categories : C#

Cannot change ObservableCollection during a CollectionChanged event
If you are using WindowsForms just make sure to use the Invoke method on the Form to keep the executing code on the Dispatcher's thread. http://msdn.microsoft.com/en-us/library/system.windows.forms.form.invoke.aspx Or, if using WPF use the Dispatcher class. http://msdn.microsoft.com/en-us/magazine/cc163328.aspx.

Categories : C#

Cannot bind ObservableCollection to List dp from xaml
How do you expect an incoming value of ObservableCollection<> type (imgList) would match with List<> type (Switch.ImageList)? Please make your types compatible. One way is to redeclare ImageListProperty to IList<> type as ObservableCollection<> implements IList interface. In WPF Binding would wouk when the target property's type is same or a base type to the source value. ObservableCollection doesnt derive from List<>. EDIT Your last example stops working because IList<> isnt instantiated implicitly (being an Interface) without explicit collection type supplied to it via XAML. Change ImageListProperty to IList (Not IList<T>). You should it change this way.... <loc:switch xmlns:coll="clr-namespace:System.Collections;assembly=mscorlib">

Categories : Wpf

ListView not updating when ObservableCollection is replaced
This is because your dependency property registration is incorrect. The name of the property passed to the Register method should be "Col", not "ColProperty": public static readonly DependencyProperty ColProperty = DependencyProperty.Register("Col", typeof(ObservableCollection<string>), typeof(ViewModel1), new PropertyMetadata(null)); The initial binding works because there is a property named Col, but it is not detected as a dependency property, so the binding is not automatically updated.

Categories : C#

Filter a list inside an observablecollection
I'm not sure if I completely understand your problem, but how about this?: Addresses.Repopulate((Repository.Addresses).Select(x => x.Types). Where(t => t.Id == 7 || t.Id == 8); Maybe if you provide more information about your class structure(s) and exactly what you want, we can provide better answers?

Categories : Wpf

Add one element to ObservableCollection / DataGrid when it becomes empty
Subscribe to the CollectionChanged event. Since the Collection cannot be modified in the CollectionChanged event, you can use the Dispatcher class and modify it. See the sample code below. void MyObservableCollection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Remove || e.Action == NotifyCollectionChangedAction.Reset) { if (MyObservableCollection.Count == 0) { Application.Current.Dispatcher.BeginInvoke(new Action(() => { MyObservableCollection.Add(new MyItem()); }), null); } } }

Categories : C#

Bind items from two different ObservableCollection to one control
You have defined the 'inner' DataGrid inside the DataGrid.RowDetailsTemplate. This Template is used to display the row details. Therefore, your SubGridItemList collection should be in the data object that is displayed in each row of the 'outer' DataGrid. So, you have a collection called GuestHostTotalList which is bound to the outer DataGrid.ItemsSource property. Whatever the type of data is in this collection is the type of data that need to add a collection property to bind to the inner DataGrid.ItemSource if you want your binding to work.

Categories : Wpf



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.