w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
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#

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#

C# - Check if ObservableCollection CollectionChanged Event has finished executing
I haven't used an ObservableCollection yet so there's the possibility I'm a touch off-base, but hey. Likely, your weakness is that you're viewing this backwards. CollectionChanged is what should be fired to let your external object accessing the collection know that the collection is updated, not to be used to update the actual collection (via dumping it out to a file or rebuilding it from an XML file). To wit: This external class should have a setup something along the lines of this: public class WeaponsEditor { private WeaponsDatabase DB; public WeaponsEditor() { DB = new WeaponsDatabase(); DB.CollectionChanged += CollectionChanged; } private object CollectionChanged(object sender, System.Collections.Specialized

Categories : C#

Raise CollectionChanged in ObservableCollection when an item's property is modified
How can I achieve the same result when an item is simply modified (such as Workers' EmployerID in this case)? You would need to subscribe to the property changed on each worker, and raise the appropriate PropertyChanged event on the resulting collection. Another option, however, would be to use WPF's built in ICollectionView filtering instead of exposing a separate property.

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#

Sort ObservableCollection bound to DataGrid in MVVM
The DataGrid uses an underlying ICollectionView based ob the DataSource, so if you directly bind a ICollectionView you can access the sorted values as the DataGrid will directly change the ICollectionView when sorting. Small Example: Code: public partial class MainWindow : Window { public MainWindow() { // dummy data source/ Your ObservableCollection var yourObservableCollection= Enumerable.Range(0, 30).Select(i => new MyType { FirstValue = i, SecondValue = i.ToString() }); // Create CollectionView based on the data you want to show MySource = CollectionViewSource.GetDefaultView(yourObservableCollection); InitializeComponent(); } public ICollectionView MySource { get; set; } private void Button_Click_1(object sender, Rout

Categories : C#

Updating any UI’s List Control’s ItemSource via adding to ObservableCollection using MVVM causing Performance Hit
What makes you think that your 'performance hit' as you call it, is caused by the code that you showed us? In my opinion, the majority of time that a WPF application takes to load data is actually taken up by the rendering engine. If you use a Stopwatch to measure the amount of time that it takes for your for loops to complete, I'm fairly sure that it won't be long at all... probably not even a quarter of a second for 50,000 objects or more: Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); foreach (var item in items) { this.Items.Add(item); } stopwatch.Stop(); TimeSpan elapsedTime = stopwatch.Elapsed; // I'm guessing this will not be a long time

Categories : Wpf

WPF,MVVM Binding ViewModel-Property to nested UserControl
Likely you have a collection of ViewModels where each of them will be a DataContext for a certain Tab. Then this ViewModel should have another collection that can be used as DataContext for your Grid or Tree.

Categories : Wpf

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#

Make TabItem select first nested button when clicked (WPF MVVM)
I think in this situation you can use Binding: TabItem <TabItem x:Name="MyTabItem" Header="Two"> <Label Content="Some Content" /> </TabItem> RadioButton <RadioButton Name="MyButton" Content="Two" IsChecked="{Binding ElementName=MyTabItem, Path=IsSelected}" /> If you want to be when you click on the RadioButton, the tab is not selected, use Mode=OneWay: <RadioButton Name="MyButton" IsChecked="{Binding ElementName=MyTabItem, Path=IsSelected, Mode=OneWay}" />

Categories : Wpf

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#

How to find out if Add or Insert was done in CollectionChanged handler
It seems counterintuitive to check it at collection level, since adding is just a special case of inserting. However, you can solve this by writing two classes: One class that extends ObservableCollection or that wraps an ObservableCollection One class that extends NotifyCollectionChangedEventArgs (let's call it MyCustomNotifyCollectionChangedEventArgs). Just define one new member to track what you need, such as a custom enum. Now just make the collection class use MyCustomNotifyCollectionChangedEventArgs instead of NotifyCollectionChangedEventArgs. In the event handler, check if the object is of type MyCustomNotifyCollectionChangedEventArgs. If it is, just cast it and read the value of the member you defined.

Categories : C#

Struts 1.1 nested and in combination
Use <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> and the code will look like <c:choose> <c:when test="${element.method1 == true}"> <c:choose> <c:when test="${element.method2 == true}"> <span style="color:green;"><c:out value="${element.prop1}/></span> </c:when> <c:otherwise> <span style="color:red;"><c:out value="${element.prop1}/></span> </c:otherwise> </c:choose> </c:when> <c:otherwise> <span style="color:black;"><c:out value="${element.prop1}/></span> </c:otherwise> </c:choose>

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#

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#

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

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#

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#

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#

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#

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#

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#

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#

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

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

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#

UI freezing when altering ObservableCollection/CollectionViewSource
I take it from your edit that this may not be the case, but if there are cases where you actually need the collection to be observable, then you can also use the CollectionViewSource.DeferRefresh() method to prevent the UI from being updated after each individual change: private async Task Search() { internalRows.Clear(); using(ViewSource.DeferRefresh()) { var data = await Task.Run(() => GetSearchResults()); if (data == null) return; foreach (ScreenerRow sRow in data) { internalRows.Add(sRow); } } } And also make sure that you have the virtualization mode set correctly on the control.

Categories : C#

ObservableCollection populated by thread from ThreadPool
You can just get your data from a background thread as a List and then cast this list to an ObservableCollection as follows List<SomeViewModel> someViewModelList = await GetYourDataAsListAsync(); ObservableCollection<SomeViewModel> Resources = new TypedListObservableCollection<SomeViewModel>(someViewModelList); I hope this helps.

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

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#



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