Search Results

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

Page 12/15 | < Previous Page | 8 9 10 11 12 13 14 15  | Next Page >

  • Bind to a collection's view and just call ToString()

    - by womp
    I'm binding a GridView to a collection of objects that look like this: public class Transaction { public string PersonName { get; set; } public DateTime TransactionDate { get; set; } public MoneyCollection TransactedMoney { get; set;} } MoneyCollection simply inherits from ObservableCollection<T>, and is a collection of MyMoney type object. In my GridView, I just want to bind a column to the MoneyCollection's ToString() method. However, binding it directly to the TransactedMoney property makes every entry display the text "(Collection)", and the ToString() method is never called. I understand that it is binding to the collection's default view. So my question is - how can I make it bind to the collection in such a way that it calls the ToString() method on it? This is my first WPF project, so I know this might be a bit noobish, but pointers would be very welcome.

    Read the article

  • wp7 and dependency property : onChanged and onRead?

    - by user233150
    hi here's my question : well I want build a wp7 control,so I write it and all go well, but the problem is that I can intercept on write(see onItemsSourcePropertyChanged)but not on read I would like explain better: public static readonly DependencyProperty ItemsSourceProperty= DependencyProperty.Register( "ItemsSource", typeof(ObservableCollection<ObjWithDesc>), typeof(HorizontalListBox), new PropertyMetadata(OnItemsSourcePropertyChanged) ); static void OnItemsSourcePropertyChanged(DependencyObject obj,DependencyPropertyChangedEventArgs e) { ((HorizontalListBox) obj).OnItemsSourcePropertyChanged(e); } OnItemsSourcePropertyChanged is called when I use SetValue(dp,..) but there isn't onItemsSourcePropertyRead ? that is called when I Use GetValue()? thanks

    Read the article

  • Silverlight Cream for March 07, 2011 -- #1055

    - by Dave Campbell
    In this Issue: Max Paulousky, Chris Rouw, David Anson, Jesse Liberty, Shawn Wildermuth, Simon Guindon, and Dhananjay Kumar. Above the Fold: Silverlight: "Faster Databinding in WPF and Silverlight using OptimizedObservableCollection" Simon Guindon WP7: "Phoney Tools Updated (WP7 Open Source Library)" Shawn Wildermuth From SilverlightCream.com: Problems With Sharing Windows Phone 7 Applications Within A Large Group Of Beta Testers Max Paulousky has a post up discussing the issues surrounding beta testing a WP7 app with a large group of testers... and how to pull it all off. WP7 Insights #1: Consuming REST APIs within a WP7 app Chris Rouw is beginning a WP7 series based on his recent experience of getting a client's app into the marketplace. This first in his series is on consuming REST APIs ... lots of good code and explanations. Improving Windows Phone 7 application performance is even easier with these LowProfileImageLoader and DeferredLoadListBox updates David Anson has an update to his LowProfileImageLoader and DeferredLoadListBox after issues brought up by readers... so we all win with the great feedback from alert devs. When Isolated Storage Isn’t Enough Jesse Liberty started looking at Jeremy Likness' Sterling with this post in the WP7 From Scratch series. He starts with downloading it from CodePlex ... great way to get into Sterling if you haven't already. Phoney Tools Updated (WP7 Open Source Library) Shawn Wildermuth has the latest drop of his Phoney Tools up... this is the last Alpha. I've added a tag for it as well. He's fixed some things, added others... check out the post and go grab the code. Faster Databinding in WPF and Silverlight using OptimizedObservableCollection Simon Guindon is a blogger I've not been following, but this post on an OptimizedObservableCollection caught my eye. He added an AddRange() to the ObservableCollection to get a speed enhancement when adding items... and a pretty good speed enhancement it is. Reading files asynchronously using WebClient class in Silverlight Dhananjay Kumar is another prolific blogger that I've not been following, so we'll start with his latest... a step-by-step guide to reading an XML file asynchronously. Stay in the 'Light! Twitter SilverlightNews | Twitter WynApse | WynApse.com | Tagged Posts | SilverlightCream Join me @ SilverlightCream | Phoenix Silverlight User Group Technorati Tags: Silverlight    Silverlight 3    Silverlight 4    Windows Phone MIX10

    Read the article

  • Dependency Property WPF Grid

    - by developer
    Hi All, I want to Bind the textblock text in WPF datagrid to a dependency property. Somehow, nothing gets displayed, but when I use the same textblock binding outside the grid, everything works fine. Below is my code, <Window.Resources> <Style x:Key="cellCenterAlign" TargetType="{x:Type toolkit:DataGridCell}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type toolkit:DataGridCell}"> <Grid Background="{TemplateBinding Background}"> <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> <Style x:Key="ColumnHeaderStyle" TargetType="{x:Type toolkit:DataGridColumnHeader}"> <Setter Property="VerticalContentAlignment" Value="Center" /> <Setter Property="HorizontalContentAlignment" Value="Center"/> </Style> <ObjectDataProvider MethodName="GetValues" ObjectType="{x:Type sys:Enum}" x:Key="RoleValues"> <ObjectDataProvider.MethodParameters> <x:Type TypeName="domain:SubscriptionRole"/> </ObjectDataProvider.MethodParameters> </ObjectDataProvider> <DataTemplate x:Key="myTemplate"> <StackPanel> <TextBlock Text="{Binding Path=OtherSubs}"/> </StackPanel> </DataTemplate> </Window.Resources> <Grid> <Grid.RowDefinitions> <RowDefinition Height="220"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <StackPanel Grid.Row="0"> <toolkit:DataGrid Name="definitionGrid" Margin="0,10,0,0" AutoGenerateColumns="False" CanUserAddRows="False" CanUserDeleteRows="False" IsReadOnly="False" RowHeight="25" FontWeight="Normal" ItemsSource="{Binding programSubscription}" ColumnHeaderStyle="{DynamicResource ColumnHeaderStyle}" SelectionMode="Single" ScrollViewer.HorizontalScrollBarVisibility="Disabled" Width="450" ScrollViewer.VerticalScrollBarVisibility="Auto" Height="200"> <toolkit:DataGrid.Columns> <toolkit:DataGridTextColumn Header="Program" Width="80" Binding="{Binding Program.JobNum}" CellStyle="{StaticResource cellCenterAlign}" IsReadOnly="True"/> <toolkit:DataGridTemplateColumn Header="Role" Width="80" CellStyle="{StaticResource cellCenterAlign}"> <toolkit:DataGridTemplateColumn.CellTemplate> <DataTemplate> <ComboBox SelectedItem="{Binding Role}" ItemsSource="{Binding Source={StaticResource RoleValues}}" Width="70"> <ComboBox.Style> <Style> <Style.Triggers> <DataTrigger Binding="{Binding Path=Role}" Value="Owner"> <Setter Property="ComboBox.Focusable" Value="False"/> <Setter Property="ComboBox.IsEnabled" Value="False"/> <Setter Property="ComboBox.IsHitTestVisible" Value="False"/> </DataTrigger> </Style.Triggers> </Style> </ComboBox.Style> </ComboBox> </DataTemplate> </toolkit:DataGridTemplateColumn.CellTemplate> </toolkit:DataGridTemplateColumn> <toolkit:DataGridCheckBoxColumn Header="Email" Width="60" Binding="{Binding ReceivesEmail}" CellStyle="{StaticResource cellCenterAlign}"/> <!--<toolkit:DataGridTextColumn Header="Others" Width="220" Binding="{Binding programSubscription1.Subscriber.Username}" CellStyle="{StaticResource cellCenterAlign}" IsReadOnly="True"/>--> <toolkit:DataGridTemplateColumn Header="Others" Width="220" CellStyle="{StaticResource cellCenterAlign}" IsReadOnly="True"> <toolkit:DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding Path=OtherSubs}"/> </DataTemplate> </toolkit:DataGridTemplateColumn.CellTemplate> </toolkit:DataGridTemplateColumn> </toolkit:DataGrid.Columns> </toolkit:DataGrid> <TextBlock Text="{Binding Path=OtherSubs}"/> </StackPanel> <Grid Grid.Row="1"> <Grid.ColumnDefinitions> <ColumnDefinition Width="200"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <StackPanel Grid.Column="0" HorizontalAlignment="Center" VerticalAlignment="Center"> <CheckBox Content="Show Only Active Programs" IsChecked="True" Margin="0,0,8,0"/> </StackPanel> <StackPanel Orientation="Horizontal" VerticalAlignment="Center" Grid.Column="1" HorizontalAlignment="Right"> <Button Content="Save" Height="23" Width="75" Margin="0,0,8,0" Click="Save_Click"/> <Button Content="Cancel" Height="23" Width="75" Margin="0,0,8,0" Click="Cancel_Click" /> </StackPanel> </Grid> </Grid> Code-Behind public partial class ProgramSubscriptions : Window { public static ObservableCollection programSubscription { get; set; } public string OtherSubs { get { return (string)GetValue(OtherSubsProperty); } set { SetValue(OtherSubsProperty, value); } } public static readonly DependencyProperty OtherSubsProperty = DependencyProperty.Register("OtherSubs", typeof(string), typeof(ProgramSubscriptions), new UIPropertyMetadata(string.Empty)); private string CurrentUsername = "test"; public ProgramSubscriptions() { InitializeComponent(); DataContext = this; LoadData(); } protected void LoadData() { programSubscription = new ObservableCollection<ProgramSubscriptionViewModel>(); if (res != null && res.TotalResults > 0) { List<ProgramSubscriptionViewModel> UserPrgList = new List<ProgramSubscriptionViewModel>(); //other.... List<ProgramSubscriptionViewModel> OtherPrgList = new List<ProgramSubscriptionViewModel>(); ArrayList myList = new ArrayList(); foreach (DomainObject obj in res.ResultSet) { ProgramSubscription prg = (ProgramSubscription)obj; if (prg.Subscriber.Username == CurrentUsername) { UserPrgList.Add(new ProgramSubscriptionViewModel(prg)); myList.Add(prg.Program.ID); } else OtherPrgList.Add(new ProgramSubscriptionViewModel(prg)); } for (int i = 0; i < UserPrgList.Count; i++) { ProgramSubscriptionViewModel item = UserPrgList[i]; programSubscription.Add(item); } //other.... for (int i = 0; i < OtherPrgList.Count; i++) { foreach (int y in myList) { ProgramSubscriptionViewModel otheritem = OtherPrgList[i]; if (y == otheritem.Program.ID) OtherSubs += otheritem.Subscriber.Username + ", "; } } } } } I posted the entire code. What exactly I want to do is in the datagridtemplatecolumn for others I want to display the usernames that are not in CurrentUsername, but they have the same program Id as the CurrentUsername. Please do let me know if there is another way that i can make this work, instead of using a dependencyproperty, althouht for testing I did put a textblock below datagrid, and it works perfectly fine.. Help!

    Read the article

  • "The calling thread cannot access this object because a different thread owns it." While using Dispa

    - by Sdry
    I have an application, that I want to load additional xaml files, being resourcedictionaries controling the style of the application. Yet when trying to add a loaded ResourceDictionary to the mergeddictionaries I get an InvalidOperationException saying "The calling thread cannot access this object because a different thread owns it." at a point where I am not even using multiple threads. The application contains a usercontrol which loads the xaml file through a background worker, adding the loaded ResourceDictionaries to an Observablecollection. When I pass on a selected theme(=ResourceDictionary) to a function in the mainwindow of the application, it goes wrong. public void LoadTheme(Theme theme) {//sdry 2010-4-22 if(theme !=null){ this._dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => { MessageBox.Show("SKIN TEST: " + theme.Name); //> oke #if (SHOWDEBUGINFO) _selectedTheme = theme.Name; //>oke #endif Application.Current.Resources.MergedDictionaries.Clear(); //>oke Application.Current.Resources.MergedDictionaries.Add(theme.ResourceDictionary); //> InvalidOperationException //the theme object has a property named ResourceDictionary of type ResourceDictionary containing the loaded xaml })); } } My first reaction was to use the Disatcher.Invoke, even not knowing how I would not be on the gui thread, which doesn't solve a thing. So maybe my loaded theme belongs to a different thread ? but its originating from a property of a usercontrol, which should be the same thread. And its accesable untill trying to use the ResourceDictionary. This makes me confused, and not very aware of how to proceed, any help is appreciated.

    Read the article

  • MVVM - ListBox SelectedItem Binding Property Going Null

    - by Peanut
    So i have a listbox: <ListBox x:Name="listbox" HorizontalAlignment="Left" Margin="8,8,0,8" Width="272" BorderBrush="{x:Null}" Background="{x:Null}" Foreground="{x:Null}" ItemsSource="{Binding MenuItems}" ItemTemplate="{DynamicResource MenuItemsTemplate}" SelectionChanged="ListBox_SelectionChanged" SelectedItem="{Binding SelectedItem}"> </ListBox> and i have this included in my viewmodel: public ObservableCollection<MenuItem> MenuItems { get { return menuitems; } set { menuitems = value; NotifyPropertyChanged("MenuItems"); } } public MenuItem SelectedItem { get { return selecteditem; } set { selecteditem = value; NotifyPropertyChanged("SelectedItem"); } } and also in my viewmodel: public void UpdateStyle() { ActiveHighlight = SelectedItem.HighlightColor; ActiveShadow = SelectedItem.ShadowColor; } So, the objective is to call UpdateStyle() whenever selectedchanged event is fired. So in the .CS file, i call UpdateStyle(). The problem is, whenever I get into the selectionchanged event method, my ViewModel.SelectedItem is always null. I tried debugging this to see if the binding was working correctly, and it is. When I click on an item in the listbox, the SelectedItem Set is triggered, setting the value... but somewhere inbetween that and the selected changed (In the CS File) It gets reset to Null. Can anyone help out? Thanks

    Read the article

  • WPF AutoCompleteBox with ability to add new values to list.

    - by WillH
    Hi, I would like to use autocompletebox with a list of values, but also add new values to the list if a user enters one that isn't present. I currently have a string property in my view model called 'Comment'. Currently this is bound to a textbox in the view - user types a comment and the view model is updated. Simple. To save time, my customer would like it to autocomplete from previous values, so the way I thought to do this is something like: ViewModel public string Comment; public ObservableCollection<string> CommentsList { ... } (populate the CommentsList when the viewmodel is created) View <AutoCompleteComboBox ItemsSource="{Binding CommentsList}" SelectedItem="{Binding Comment, Mode=TwoWay/> So when the user selects a value, it saves the value in the Comment property. This works fine if the user selects an item in the list, but if the user types in a new value, the comment property is not updated (it is null because the selected item was not in the list). Is this possible with autocompletebox? Thanks in advance, Will

    Read the article

  • How to handle ViewModel and Database in C#/WPF/MVVM App

    - by Mike B
    I have a task management program with a "Urgency" field. Valid values are Int16 currently mapped to 1 (High), 2 (Medium), 3 (Low), 4 (None) and 99 (Closed). The urgency field is used to rank tasks as well as alter the look of the items in the list and detail view. When a user is editing or adding a new task they select or view the urgency in a ComboBox. A Converter passes Strings to replace the Ints. The urgency collection is so simple I did not make it a table in the database, instead it is a, ObservableCollection(Int16) that is populated by a method. Since the same screen may be used to view a closed task the "Closed" urgency must be in the ItemsSource but I do not want the user to be able to select it. In order to prevent the user from being able to select that item in the ComboBox but still be able to see it if the item in the database has that value should I... Manually disable the item in the ComboBox in code or Xaml (I doubt it) Change the Urgency collection from an Int16 to an Object with a Selectable Property that the isEnabled property of the ComboBoxItem Binds to. Do as in 2 but also separate the urgency information into its own table in the database with a foreign key in the Tasks table None of the above (I suspect this is the correct answer) I ask this because this is a learning project (My first real WPF and first ever MVVM project). I know there is rarely one Right way to do something but I want to make sure I am learning in a reasonable manner since it if far harder to Unlearn bad habits Thanks Mike

    Read the article

  • I got MVVM 3-Level-Master-Detail Switchting working but with CRUD operations now everything seems st

    - by msfanboy
    Hello, I have 1 UserControl (SchoolclassAdministration.xaml) that is datatemplated with 1 ViewModel (SchoolclassAdministrationViewModel) I have 3 Models and 3 ViewModels in that scenario. Those 3 ViewModels must reflect the requirements of the View. The requirements are 3 "Areas" on the left side and 2 "Areas" on the right side. 3: SchoolclassFormular PupilFormular SubjectFormular Those have all Buttons for Add/Delete 2: PupilsDataGrid SubjectsDataGrid The Master-Detail scenario is between the: SchoolclassFormular = PupilsDataGrid = SubjectsDataGrid The switching of the ViewModelCollections work! My Problem scenario is this: The DataContext is on the SchoolclassAdministrationViewModel what is the ViewModel containing the AllSchoolclassesViewModel ObservableCollection bound to the SchoolclassAdministration.xaml UserControl. My SchoolclassViewModel,PupilViewModel and SubjectViewModel has all Properties, Commands(Add/Delete). My Question: How can I set these 3 ViewModels as DataContext to my ONE SchoolclassAdministration.xaml UserControl I have? Before you answer... putting every ViewModel(schoolclass,pupil,subject) in its own UserControl will not help me because then the Master-Detail switching can NOT work anymore. Every related ViewModels need to be put in a related/ONE UserControl. OK now I can`t wait for an answer because that scenario is driving me nuts for weeks.

    Read the article

  • WPF Repeater (like) control for collection source??

    - by Sonic Soul
    I have a WPF DataGrid bound to ObservableCollection. Each item in my collection has Property which is a List. In my row details pane, i would like to write out formatted textblocks for each item in this collection. The end result would be something equivalent to: <TextBlock Style="{StaticResource NBBOTextBlockStyle}" HorizontalAlignment="Right"> <TextBlock.Inlines> <Run FontWeight="Bold" Text="{Binding Path=Exchanges[0].Name}" /> <Run FontWeight="Bold" Text="{Binding Path=Exchanges[0].Price}" /> <LineBreak /> <Run Foreground="LightGray" Text="{Binding Path=Exchanges[0].Quantity}" /> </TextBlock.Inlines> </TextBlock> <TextBlock Style="{StaticResource NBBOTextBlockStyle}"> <TextBlock.Inlines> <Run FontWeight="Bold" Text="{Binding Path=Exchanges[1].Name}" /> <Run FontWeight="Bold" Text="{Binding Path=Exchanges[1].Price}" /> <LineBreak /> <Run Foreground="LightGray" Text="{Binding Path=Exchanges[1].Quantity}" /> </TextBlock.Inlines> </TextBlock> and so on 0-n times. I've tried using ItemsControl for this: <ItemsControl ItemsSource="{Binding Path=Exchanges}"> <DataTemplate> <Label>test</Label> </DataTemplate> </ItemsControl> however, this appears to be only meant for more static sources, as it throws the following exception (collection is not altered after creation): ItemsControl Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead Is there another way to achieve this?

    Read the article

  • Error Cannot create an Instance of "ObjectName" in Designer when using <UserControl.Resources>

    - by Mike Bynum
    Hi All, I'm tryihg to bind a combobox item source to a static resource. I'm oversimplfying my example so that it's easy to understand what i'm doing. So I have created a class public class A : ObservableCollection<string> { public A() { IKBDomainContext Context = new IKBDomainContext(); Context.Load(Context.GetIBOptionsQuery("2C6C1Q"), p => { foreach (var item in SkinContext.IKBOptions) { this.Add(item); } }, null); } } So the class has a constructor that populates itself using a domaincontext that gets data from a persisted database. I'm only doing reads on this list so dont have to worry about persisting back. in xaml i add a reference to the namespace of this class then I add it as a usercontrol.resources to the page control. <UserControl.Resources> <This:A x:Key="A"/> </UserControl.Resources> and then i use it this staticresource to bind it to my combobox items source.in reality i have to use a datatemplate to display this object properly but i wont add that here. <Combobox ItemsSource="{StaticResource A}"/> Now when I'm in the designer I get the error: Cannot Create an Instance of "A". If i compile and run the code, it runs just fine. This seems to only affect the editing of the xaml page. What am I doing wrong?

    Read the article

  • Moq for Silverlight doesn't raise event

    - by Budda
    Trying to write Unit test for Silverlight 4.0 using Moq 4.0.10531.7 public delegate void DataReceived(ObservableCollection<TeamPlayerData> AllReadyPlayers, GetSquadDataCompletedEventArgs squadDetails); public interface ISquadModel : IModelBase { void RequestData(int matchId, int teamId); void SaveData(); event DataReceived DataReceivedEvent; } void MyTest() { Mock<ISquadModel> mockSquadModel = new Mock<ISquadModel>(); mockSquadModel.Raise(model => model.DataReceivedEvent += null, EventArgs.Empty); } Instead of raising the 'DataReceivingEvent' the following error is received: Object of type 'Castle.Proxies.ISquadModelProxy' cannot be converted to type 'System.Collections.ObjectModel.ObservableCollection`1[TeamPlayerData]'. Why attempt to convert mock to the type of 1st event parameter is performed? How can I raise an event? I've also tried another approach: mockSquadModel .Setup(model => model.RequestData(TestMatchId, TestTeamId)) .Raises(model => model.DataReceivedEvent += null, EventArgs.Empty) ; this should raise event if case somebody calls 'Setup' method... Instead the same error is generated... Any thoughts are welcome. Thanks

    Read the article

  • Why is "Fixup" needed for Persistence Ignorant POCO's in EF 4?

    - by Eric J.
    One of the much-anticipated features of Entity Framework 4 is the ability to use POCO (Plain Old CLR Objects) in a Persistence Ignorant manner (i.e. they don't "know" that they are being persisted with Entity Framework vs. some other mechanism). I'm trying to wrap my head around why it's necessary to perform association fixups and use FixupCollection in my "plain" business object. That requirement seems to imply that the business object can't be completely ignorant of the persistence mechanism after all (in fact the word "fixup" sounds like something needs to be fixed/altered to work with the chosen persistence mechanism). Specifically I'm referring to the Association Fixup region that's generated by the ADO.NET POCO Entity Generator, e.g.: #region Association Fixup private void FixupImportFile(ImportFile previousValue) { if (previousValue != null && previousValue.Participants.Contains(this)) { previousValue.Participants.Remove(this); } if (ImportFile != null) { if (!ImportFile.Participants.Contains(this)) { ImportFile.Participants.Add(this); } if (ImportFileId != ImportFile.Id) { ImportFileId = ImportFile.Id; } } } #endregion as well as the use of FixupCollection. Other common persistence-ignorant ORMs don't have similar restrictions. Is this due to fundamental design decisions in EF? Is some level of non-ignorance here to stay even in later versions of EF? Is there a clever way to hide this persistence dependency from the POCO developer? How does this work out in practice, end-to-end? For example, I understand support was only recently added for ObservableCollection (which is needed for Silverlight and WPF). Are there gotchas in other software layers from the design requirements of EF-compatible POCO objects?

    Read the article

  • Bind to a method in WPF?

    - by Cameron MacFarland
    How do you bind to an objects method in this scenario in WPF? public class RootObject { public string Name { get; } public ObservableCollection<ChildObject> GetChildren() {...} } public class ChildObject { public string Name { get; } } XAML: <TreeView ItemsSource="some list of RootObjects"> <TreeView.Resources> <HierarchicalDataTemplate DataType="{x:Type data:RootObject}" ItemsSource="???"> <TextBlock Text="{Binding Path=Name}" /> </HierarchicalDataTemplate> <HierarchicalDataTemplate DataType="{x:Type data:ChildObject}"> <TextBlock Text="{Binding Path=Name}" /> </HierarchicalDataTemplate> </TreeView.Resources> </TreeView> Here I want to bind to the GetChildren method on each RootObject of the tree. EDIT Binding to an ObjectDataProvider doesn't seem to work because I'm binding to a list of items, and the ObjectDataProvider needs either a static method, or it creates it's own instance and uses that. For example, using Matt's answer I get: System.Windows.Data Error: 33 : ObjectDataProvider cannot create object; Type='RootObject'; Error='Wrong parameters for constructor.' System.Windows.Data Error: 34 : ObjectDataProvider: Failure trying to invoke method on type; Method='GetChildren'; Type='RootObject'; Error='The specified member cannot be invoked on target.' TargetException:'System.Reflection.TargetException: Non-static method requires a target.

    Read the article

  • RelayCommand sender from ItemsControl item

    - by Padu Merloti
    I've been using MVVM's RelayCommand with success to bind actions to XAML, but I'm having a small problem with my ItemsControl. <ItemsControl ItemsSource="{Binding Devices}" > <ItemsControl.ItemTemplate> <DataTemplate> <Grid Width="100" Margin="4" > <Button Command="{Binding Path=SelectDeviceCommand}" > <Grid> <Image Source="img_small.png"></Image> <Image Source="{Binding Path=Logo}" /> </Grid> </Button> </Grid> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> In my view model: public RelayCommand SelectDeviceCommand { get; set; } private ObservableCollection<Device> Devices; Devices = CreateListOfDevices(); private void InitializeCommands() { SelectDeviceCommand = new RelayCommand((s) => MessageBox.Show(s.ToString())); } How do I define my SelectDeviceCommand in my view model in order to receive object that is bound to that item? My SelectDeviceCommand is not even being called... (but that I guess is because I need to make my Device a mini-viewmodel and implement the SelectDeviceCommand in it, is that correct?)

    Read the article

  • Implementing BindingList<T>

    - by EtherealMonkey
    I am trying to learn more about BindingList because I believe that it will help me with a project that I am working on. Currently, I have an object class (ScannedImage) that is a subtype of a class (HashedImage) that subtypes a native .Net object (Image). There is no reason why I couldn't move the two subtypes together. I am simply subtyping an object that I had previously constructed, but I will now be storing my ScannedImage object in an RDB (well, not technically - only the details and probably the thumbnail). Also, the object class has member types that are my own custom types (Keywords). I am using a custom datagridview to present these objects, but am handling all changes to the ScannedImage object with my own code. As you can probably imagine, I have quite a few events to handle that occur in these base types. So, if I changed my object to implement INotifyPropertyChanged, would the object collection (implementing BindingList) receive notifications of changes to the ScannedImage object? Also, if Keywords were to implement INotifyPropertyChanged, would changes be accessible to the BindingList through the ScannedImage object? Sorry if this seems rather newbish. I only recently discovered the BindingList and not having formal training in C# programming - am having a difficult time moving forward with this. Also, if anyone has any good reference material, I would be thankful for links. Obviously, I have perused the MSDN Library. I have found a few good links on the web, but it seems that a lot of people are now using WPF and ObservableCollection. My project is based on Winforms and .Net3.5 framework. TIA

    Read the article

  • WPF/Silverlight AutoCompleteBox with ability to add new values to list.

    - by WillH
    Hi, I would like to use autocompletebox with a list of values, but also add new values to the list if a user enters one that isn't present. I currently have a string property in my view model called 'Comment'. Currently this is bound to a textbox in the view - user types a comment and the view model is updated. Simple. To save time, my customer would like it to autocomplete from previous values, so the way I thought to do this is something like: ViewModel public string Comment; public ObservableCollection<string> CommentsList { ... } (populate the CommentsList when the viewmodel is created) View <AutoCompleteComboBox ItemsSource="{Binding CommentsList}" SelectedItem="{Binding Comment, Mode=TwoWay/> So when the user selects a value, it saves the value in the Comment property. This works fine if the user selects an item in the list, but if the user types in a new value, the comment property is not updated (it is null because the selected item was not in the list). Is this possible with autocompletebox? Thanks in advance, Will

    Read the article

  • Can a WPF ComboBox display alternative text when its selection is null?

    - by Garth T Kidd
    G'day! I want my WPF ComboBox to display some alternative text when its data-bound selection is null. The view model has the expected properties: public ThingoSelectionViewModel : INotifyPropertyChanged { public ThingoSelectionViewModel(IProvideThingos) { this.Thingos = IProvideThingos.GetThingos(); } public ObservableCollection<Thingo> Thingos { get; set; } public Thingo SelectedThingo { get { return this.selectedThingo; } set { // set this.selectedThingo and raise the property change notification } // ... } The view has XAML binding to the view model in the expected way: <ComboBox x:Name="ComboboxDrive" SelectedItem="{Binding Path=SelectedThingo}" IsEditable="false" HorizontalAlignment="Left" MinWidth="100" IsReadOnly="false" Style="{StaticResource ComboboxStyle}" Grid.Column="1" Grid.Row="1" Margin="5" SelectedIndex="0"> <ComboBox.ItemsSource> <CompositeCollection> <ComboBoxItem IsEnabled="False">Select a thingo</ComboBoxItem> <CollectionContainer Collection="{Binding Source={StaticResource Thingos}}" /> </CompositeCollection> </ComboBox.ItemsSource> </ComboBox> The ComboBoxItem wedged into the top is a way to get an extra item at the top. It's pure chrome: the view model stays pure and simple. There's just one problem: the users want "Select a thingo" displayed whenever the ComboBox' selection is null. The users do not want a thingo selected by default. They want to see a message telling them to select a thingo. I'd like to avoid having to pollute the viewmodel with a ThingoWrapper class with a ToString method returning "Select a thingo" if its .ActualThingo property is null, wrapping each Thingo as I populate Thingos, and figuring out some way to prevent the user from selecting the nulled Thingo. Is there a way to display "Select a thingo" within the ComboBox' boundaries using pure XAML, or pure XAML and a few lines of code in the view's code-behind class?

    Read the article

  • WPF HiercharchicalDataTemplate.DataType: How to react on interfaces?

    - by David Schmitt
    Problem I've got a collection of IThings and I'd like to create a HierarchicalDataTemplate for a TreeView. The straightforward DataType={x:Type local:IThing} of course doesn't work, probably because the WPF creators didn't want to handle the possible ambiguities. Since this should handle IThings from different sources at the same time, referencing the implementing class is out of question. Current solution For now I'm using a ViewModel which proxies IThing through a concrete implementation: public interface IThing { string SomeString { get; } ObservableCollection<IThing> SomeThings { get; } // many more stuff } public class IThingViewModel { public IThing Thing { get; } public IThingViewModel(IThing it) { this.Thing = it; } } <!-- is never applied --> <HierarchicalDataTemplate DataType="{x:Type local:IThing}"> <!-- is applied, but looks strange --> <HierarchicalDataTemplate DataType="{x:Type local:IThingViewModel}" ItemsSource="{Binding Thing.SomeThings}"> <TextBox Text="{Binding Thing.SomeString}"/> </HierarchicalDataTemplate> Question Is there a better (i.e. no proxy) way?

    Read the article

  • Quick MEF + SL4 question

    - by Tom Allen
    I'm working on an app in the Silverlight 4 RC and i'm taking the oppertunity to learn MEF for handling plugin controls. I've got it working in a pretty basic manor, but it's not exactly tidy and I know there is a better way of importing multiple xap's. Essentially, in the App.xaml of my host app, I've got the following telling MEF to load my xap's: AggregateCatalog catalog = new AggregateCatalog(); DeploymentCatalog c1 = new DeploymentCatalog(new Uri("TestPlugInA.xap", UriKind.Relative)); DeploymentCatalog c2 = new DeploymentCatalog(new Uri("TestPlugInB.xap", UriKind.Relative)); catalog.Catalogs.Add(c1); catalog.Catalogs.Add(c2); CompositionHost.Initialize(catalog); c1.DownloadAsync(); c2.DownloadAsync(); I'm sure I'm not using the AggregateCatalog fully here and I need to be able to load any xap's that might be in the directory, not just hardcoding Uri's obviously.... Also, in the MainPage.xaml.cs in the host I have the following collection which MEF puts the plugin's into: [ImportMany(AllowRecomposition = true)] public ObservableCollection<IPlugInApp> PlugIns { get; set; } Again, this works, but I'm pretty sure I'm using ImportMany incorrectly.... Finally, the MainPage.xaml.cs file implements IPartImportsSatisfiedNotification and I have the following for handling the plugin's once loaded: public void OnImportsSatisfied() { sp.Children.Clear(); foreach (IPlugInApp plugIn in PlugIns) { if (plugIn != null) sp.Children.Add(plugIn.GetUserControl()); } } This works, but it seems filthy that it runs n times (n being the number of xap's to load). I'm having to call sp.Children.Clear() as if I don't, when loading the 2 plugin's, my stack panel is populated as follows: TestPlugIn A TestPlugIn A TestPlugIn B I'm clearly missing something here. Can anyone point out what I should be doing? Thanks!

    Read the article

  • Silverlight Toolkit ListBoxDragTarget Only One Way

    - by Tom Allen
    I've got a Silverlight 3 app that has two ListBoxes that I need to be able to drag items between. I've got the toolkit control working so that I can drag from ListBox lbA to ListBox lbB but i then can't drag the item from lbB back to lbA. <toolkit:ListBoxDragDropTarget mswindows:DragDrop.AllowDrop="True"> <ListBox x:Name="lbA" Style="{StaticResource ListBoxStyle}"> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding DisplayMember}"/> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </toolkit:ListBoxDragDropTarget> <toolkit:ListBoxDragDropTarget mswindows:DragDrop.AllowDrop="True"> <ListBox x:Name="lbB" Style="{StaticResource ListBoxStyle}" Width="350"> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding DisplayMember}"/> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </toolkit:ListBoxDragDropTarget> I'm binding lbA to an ObservableCollection of MyObject items which is a parent class for objects MyObjectA and MyObjectB (and there is a mix of ChildObjectA and ChildObjectB items). Is the one way behaviour I'm seeing due to binding to a collection MyObjects or something else i'm missing?

    Read the article

  • WPF : Multiple views, one DataContext

    - by zapho
    Hi, I'm working on a WPF application which must handle multiple screens (two at this this time). One view can be opened on several screens and user actions must be reflected consistently on all screens. To achieve this, for a given type of view, a single DataContext is instantiated. Then, when a view is displayed on a screen, the unique DataContext is attached to it. So, one DataContext, several views (same type of view/xaml). So far so good. It works quite well in most cases. I do have a problem with a specific view which relies on ItemsControl. These ItemsControl are used to display UIElements dynamically build in the ViewModel/DataContext (C# code). These UIElements are mostly Path objects. Example : <ItemsControl ItemsSource="{Binding WindVectors}"> <ItemsControl.Template> <ControlTemplate TargetType="{x:Type ItemsControl}"> <Canvas IsItemsHost="True" /> </ControlTemplate> </ItemsControl.Template> </ItemsControl> Here, WindVectors is a ObservableCollection<UIElement>. When the view is opened the first time, everything is fine. The problem is that when the view is opened one another screen, all ItemsControl are removed from the first screen and displayed one the second screen. Other WPF components (TextBlock for instance) on this view react normally and are displayed on both screens. Any help would be greatly appreciated. Thanks. Fabrice

    Read the article

  • Implement master detail in one datagrid in wpf

    - by Archie
    Hello, I have classes as following: public class Property { public string PropertyName { get; set; } public int SumSubPropertValue; private List<SubProperty> propertyList; public void CalculateSumSubPropertValue { // implementation} } public class SubProperty { public string SubPropertyName { get; set; } public int SubPropertyValue { get; set; } } I have grouped the rows in datagrid on PropertyName . When the user clicks on PropertyName expnader the columns should display SubPropertyName and SubPropertyValue. Also SumSubPropertValue should appear in front of PropertyName in the expander header. My Datagrid is bound to a CollectionViewSource as follows: CollectionViewSource view = new CollectionViewSource(); view.Source = infoList; view.GroupDescriptions.Add(new PropertyGroupDescription("PropertyName")); Where infoList is ObservableCollection<Property>. My datagrid colmns look like <my:DataGrid.Columns> <my:DataGridTextColumn Header="SubPropertyName" Binding="{Binding SubPropertName}" Width="*"/> <my:DataGridTextColumn Header="SubPropertyValue" Binding="{Binding SubPropertyValue}" Width="*"/> </my:DataGrid.Columns> Can someone help me with it?

    Read the article

  • Manipulating collections & the ViewModel pattern

    - by Kragen
    I'm relatively new to WPF, and I'm having trouble with what I'm fairly certain is a relatively simple problem. I have my underlying data object, a Person: class Person { public string Surname {get; set; } public string Firstname {get; set; } public List<Address> Addresses {get; } } And I wish to display and edit this object in my WPF app. To this end I've created a ViewModel that I bind to in my xaml: class PersonViewModel { public string Fullname {get; } public ObservableCollection<AddressViewModel> Addresses {get; } } This is fine, except when it comes to manipulating my Address collection, where I can't work out what I should be doing: Should I add methods AddAddress, RemoveAddress etc... to my PersonViewModel class for manipulating my collection with instances of AddressViewModel Should I just add instances of AddressViewModel to my Addresses observable collection Both of the above seem a bit messy - is there a better way of dealing with collections?

    Read the article

  • Horrorble performance using ListViews with nested objects in WPF

    - by Christian
    Hi community, like mentioned in the title I get a horrible performance if I use ListViews with nested objects. My scenario is: Each row of a ListView presents an object of the class Transaction with following attributes: private int mTransactionID; private IBTTransactionSender mSender; private IBTTransactionReceiver mReceiver; private BTSubstrate mSubstrate; private double mAmount; private string mDeliveryNote; private string mNote; private DateTime mTransactionDate; private DateTime mCreationTimestamp; private BTEmployee mEmployee; private bool mImported; private bool mDescendedFromRecurringTransaction; Each attribute can be accessed by its corresponding property. An ObservableCollection<Transaction> is bound to the ItemsSource of a ListView. The ListView itself looks like the following: </ListView.GroupStyle> <ListView.View> <GridView> <GridViewColumn core:SortableListView.SortPropertyName="Transaction.ToSave" Width="80"> <GridViewColumnHeader Name="GVCHLoadedToSave" Style="{StaticResource ListViewHeaderStyle}">Speichern</GridViewColumnHeader> <GridViewColumn.CellTemplate> <DataTemplate> <Grid> <CheckBox Name="CBListViewItem" IsChecked="{Binding Path=Transaction.ToSave, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></CheckBox> </Grid> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn core:SortableListView.SortPropertyName="Transaction.TransactionDate" Width="80"> <GridViewColumnHeader Name="GVCHLoadedDate" Style="{StaticResource ListViewHeaderStyle}">Datum</GridViewColumnHeader> <GridViewColumn.CellTemplate> <DataTemplate> <Grid> <TextBlock Text="{Binding ElementName=DPDate, Path=Text}" Style="{StaticResource GridBlockStyle}"/> <toolkit:DatePicker Name="DPDate" Width="{Binding ElementName=GVCHDate, Path=ActualWidth}" SelectedDateFormat="Short" Style="{StaticResource GridEditStyle}" SelectedDate="{Binding Path=Transaction.TransactionDate, Mode=TwoWay}" SelectedDateChanged="DPDate_SelectedDateChanged"/> </Grid> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn core:SortableListView.SortPropertyName="Transaction.Sender.Description" Width="120"> <GridViewColumnHeader Name="GVCHLoadedSender" Style="{StaticResource ListViewHeaderStyle}">Von</GridViewColumnHeader> <GridViewColumn.CellTemplate> <DataTemplate> <Grid> <TextBlock Text="{Binding Path=Transaction.Sender.Description}" Style="{StaticResource GridBlockStyle}"/> <ComboBox Name="CBSender" Width="{Binding ElementName=GVCHSender, Path=ActualWidth}" SelectedItem="{Binding Path=Transaction.Sender}" DisplayMemberPath="Description" Text="{Binding Path=Sender.Description, Mode=OneWay}" ItemsSource="{Binding ElementName=Transaction, Path=SenderList}" Style="{StaticResource GridEditStyle}"> </ComboBox> </Grid> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn core:SortableListView.SortPropertyName="Transaction.Receiver.Description" Width="120"> <GridViewColumnHeader Name="GVCHLoadedReceiver" Style="{StaticResource ListViewHeaderStyle}">Nach</GridViewColumnHeader> <GridViewColumn.CellTemplate> <DataTemplate> <Grid> <TextBlock Text="{Binding Path=Transaction.Receiver.Description}" Style="{StaticResource GridBlockStyle}"/> <ComboBox Name="CBReceiver" Width="{Binding ElementName=GVCHReceiver, Path=ActualWidth}" SelectedItem="{Binding Path=Transaction.Receiver}" DisplayMemberPath="Description" Text="{Binding Path=Receiver.Description, Mode=OneWay}" ItemsSource="{Binding ElementName=Transaction, Path=ReceiverList}" Style="{StaticResource GridEditStyle}"> </ComboBox> </Grid> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn core:SortableListView.SortPropertyName="Transaction.Substrate.Description" Width="140"> <GridViewColumnHeader Name="GVCHLoadedSubstrate" Style="{StaticResource ListViewHeaderStyle}">Substrat</GridViewColumnHeader> <GridViewColumn.CellTemplate> <DataTemplate> <Grid> <TextBlock Text="{Binding Path=Transaction.Substrate.Description}" Style="{StaticResource GridBlockStyle}"/> <ComboBox Name="CBSubstrate" Width="{Binding ElementName=GVCHSubstrate, Path=ActualWidth}" SelectedItem="{Binding Path=Transaction.Substrate}" DisplayMemberPath="Description" Text="{Binding Path=Substrate.Description, Mode=OneWay}" ItemsSource="{Binding ElementName=Transaction, Path=SubstrateList}" Style="{StaticResource GridEditStyle}"> </ComboBox> </Grid> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn core:SortableListView.SortPropertyName="Transaction.Amount" Width="80"> <GridViewColumnHeader Name="GVCHLoadedAmount" Style="{StaticResource ListViewHeaderStyle}">Menge [kg]</GridViewColumnHeader> <GridViewColumn.CellTemplate> <DataTemplate> <Grid> <TextBlock Text="{Binding Path=Transaction.Amount}" Style="{StaticResource GridBlockStyle}"/> <TextBox Name="TBAmount" Text="{Binding Path=Transaction.Amount, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="{Binding ElementName=GVCHAmount, Path=ActualWidth}" Style="{StaticResource GridTextBoxStyle}" /> </Grid> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn core:SortableListView.SortPropertyName="Transaction.DeliveryNote" Width="100"> <GridViewColumnHeader Name="GVCHLoadedDeliveryNote" Style="{StaticResource ListViewHeaderStyle}">Lieferschein Nr.</GridViewColumnHeader> <GridViewColumn.CellTemplate> <DataTemplate> <Grid> <TextBlock Text="{Binding Path=Transaction.DeliveryNote}" Style="{StaticResource GridBlockStyle}"/> <TextBox Name="TBDeliveryNote" Text="{Binding Path=Transaction.DeliveryNote, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="{Binding ElementName=GVCHDeliveryNote, Path=ActualWidth}" Style="{StaticResource GridEditStyle}" /> </Grid> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn core:SortableListView.SortPropertyName="Transaction.Note" Width="190"> <GridViewColumnHeader Name="GVCHLoadedNote" Style="{StaticResource ListViewHeaderStyle}">Bemerkung</GridViewColumnHeader> <GridViewColumn.CellTemplate> <DataTemplate> <Grid> <TextBlock Text="{Binding Path=Transaction.Note}" Style="{StaticResource GridBlockStyle}"/> <TextBox Name="TBNote" Text="{Binding Path=Transaction.Note, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="{Binding ElementName=GVCHNote, Path=ActualWidth}" Style="{StaticResource GridEditStyle}" /> </Grid> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn core:SortableListView.SortPropertyName="Transaction.Employee.LastName" Width="100"> <GridViewColumnHeader Name="GVCHLoadedEmployee" Style="{StaticResource ListViewHeaderStyle}">Mitarbeiter</GridViewColumnHeader> <GridViewColumn.CellTemplate> <DataTemplate> <Grid> <TextBlock Text="{Binding Path=Transaction.Employee.LastName}" Style="{StaticResource GridBlockStyle}"/> <ComboBox Name="CBEmployee" Width="{Binding ElementName=GVCHEmployee, Path=ActualWidth}" SelectedItem="{Binding Path=Transaction.Employee}" DisplayMemberPath="LastName" Text="{Binding Path=Employee.LastName, Mode=OneWay}" ItemsSource="{Binding ElementName=Transaction, Path=EmployeeList}" Style="{StaticResource GridEditStyle}"> </ComboBox> </Grid> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> </GridView> </ListView.View> </ListView> As you can see in the screenshot the user got the possibility to change the values of the transaction attributes with comboboxes. Ok now to my problem. If I click on the "Laden" button the application will load about 150 entries in the ObservableCollection<Transaction>. Before I fill the collection I set the ItemsSource of the ListView to null and after filling I bind the collection to the ItemsSource once again. The loading itself takes a few milliseconds, but the rendering of the filled collection takes a long time (150 entries = about 20 sec). I tested to delete all Comboboxes out of the xaml and i got a better performance, because I don't have to fill the ComboBoxes for each row. But I need to have these comboboxes for modifing the attributes of the Transaction. Does anybody know how to improve the performance? THX

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15  | Next Page >