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#

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#

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#

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#

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#

WPF Binding filtered ObservableCollection ICollectionView to Combobox
Filtering by type is easy. This should work: location.Filter = p => p.GetType() == typeof(AddPoint); Sorting is also quite easy. All you need to do is to implement IComparer and assign it to CustomSort property of collection view. There is no easy way to remove duplicates tho (not that i am aware of). I suggest you to do it elsewhere. For example, you could distinct your underlying collection.

Categories : C#

DataGrid not binding (XAML + ViewModel + ObservableCollection)
Edit: I suspect the DataGrid updates just fine but you can't see it because the FilesAreQueued property is lying. You would need something like FilesToAdd.CollectionChanged += (s,e) => OnPropertyChanged("FilesAreQueued"); As you only want to do that once (if at all, can bind to FilesToAdd.Count directly), you really should opt for a readonly collection field. Looks fine if the DataContext of the view is actually that view-model. Another issue could be that the class is not implementing INotifyPropertyChanged (you can have the event without actually implementing it using class : interface), this would only apply if you overwrite the FilesToAdd property with a new instance. (In general i expose collections as get-only with a readonly field.) Might want to check for binding er

Categories : Wpf

Binding ListBoxItem properties when ListBox is bound to ObservableCollection
The DataTemplate specifies the template (UI presentation) of the content of the list box item. What you need to style is the item container itself which can be done via the ItemContainerStyle property of the ListBox.

Categories : C#

Multiple pages accessing (binding) ObservableCollection from MainPage.cs
You should be using Mvvm. Try checking out Mvvm Light, as it's quite easy to implement. Basically, you put all of your data (described as a "Model" in the "Model-View-ViewModel" design, abbreviated Mvvm) into a "ViewModel" object. In this case, your ObservableCollection. Then all of your pages bind directly into your ViewModel. Mvvm creates a static "ViewModelLocator" that allows you to set the Source of all of your Bindings, and get it to work quite easily.

Categories : C#

Elegant way of binding combobox in datagrid with a new reference of ObservableCollection
There's no point in using ObservableCollection if you overwrite it whole, just edit its contents. I for one never even provide a setter on those collection properties. (Implementation note: You can record all the CollectionChanged events in the dialog and apply their modifications to the original collection)

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#

adding an object to an ObservableCollection makes two UI items appear
Does the same behaviour happen if you use an MVxListView? If it doesn't, then it sounds like you've hit a bug in the linearlayout binding - in which case the best place to log that is: https://github.com/slodge/MvvmCross/issues/new - or you can try to solve the error yourself - https://github.com/slodge/MvvmCross/blob/v3/Cirrious/Cirrious.MvvmCross.Binding.Droid/Views/MvxLinearLayout.cs If it does, then I suspect there is a bug in your logic somewhere.

Categories : Android

Java how to handle "Unchecked cast" for Array from Object
You cannot do it without a warning. You are casting an Object to some other class, and even if the Object is an instance of ArrayList you don't know it's generic type.

Categories : Java

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#

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

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

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#

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#

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#

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

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 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#

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#

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#

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#

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#

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#

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#

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#

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#

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

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#

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#

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#

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#

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

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#



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