Search Results

Search found 253 results on 11 pages for 'inotifypropertychanged'.

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

  • Silverlight Cream for April 02, 2010 -- #828

    - by Dave Campbell
    In this Issue: Phil Middlemiss, Robert Kozak, Kathleen Dollard, Avi Pilosof, Nokola, Jeff Wilcox, David Anson, Timmy Kokke, Tim Greenfield, and Josh Smith. Shoutout: SmartyP has additional info up on his WP7 Pivot app: Preview of My Current Windows Phone 7 Pivot Work From SilverlightCream.com: A Chrome and Glass Theme - Part I Phil Middlemiss is starting a tutorial series on building a new theme for Silverlight, in this first one we define some gradients and color resources... good stuff Phil Intercepting INotifyPropertyChanged This is Robert Kozak's first post on this blog, but it's a good one about INotifyPropertyChanged and MVVM and has a solution in the post with lots of code and discussion. How do I Display Data of Complex Bound Criteria in Horizontal Lists in Silverlight? Kathleen Dollard's latest article in Visual Studio magazine is in answer to a question about displaying a list of complex bound criteria including data, child data, and photos, and displaying them horizontally one at a time. Very nice-looking result, and all the code. Windows Phone: Frame/Page navigation and transitions using the TransitioningContentControl Avi Pilosof discusses the built-in (boring) navigation on WP7, and then shows using the TransitionContentControl from the Toolkit to apply transitions to the navigation. EasyPainter: Cloud Turbulence and Particle Buzz Nokola returns with a couple more effects for EasyPainter: Cloud Turbulence and Particle Buzz ... check out the example screenshots, then go grab the code. Property change notifications for multithreaded Silverlight applications Jeff Wilcox is discussing the need for getting change notifications to always happen on the UI thread in multi-threaded apps... great diagrams to see what's going on. Tip: The default value of a DependencyProperty is shared by all instances of the class that registers it David Anson has a tip up about setting the default value of a DependencyProperty, and the consequence that may have depending upon the type. Building a “real” extension for Expression Blend Timmy Kokke's code is WPF, but the subject is near and dear to us all, Timmy has a real-world Expression Blend extension up... a search for controls in the Objects and Timelines pane ... and even if that doesn't interest you... it's the source to a Blend extension! XPath support in Silverlight 4 + XPathPad Tim Greenfield not only talks about XPath in SL4RC, but he has produced a tool, XPathPad, and provided the source... if you've used XPath, you either are a higher thinker than me(not a big stretch), or you need this :) Using a Service Locator to Work with MessageBoxes in an MVVM Application Josh Smith posted about a question that comes up a lot: showing a messagebox from a ViewModel object. This might not work for custom message boxes or unit testing. This post covers the Unit Testing aspect. 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

  • Utilisez WCF Data Services 1.5 avec Silverlight, par Benjamin Roux

    Citation: Cet article vous présentera comment utiliser Silverlight et WCF Data Services 1.5. Premièrement, pourquoi utiliser Data Services 1.5 ? Tout simplement parce que l'intégration avec Silverlight est grandement améliorée (INotifyPropertyChanged et ObservableCollection, Two-way binding.). c'est par ici N'hésitez pas à laisser vos commentaires ici même

    Read the article

  • Nested property binding

    - by EtherealMonkey
    Recently, I have been trying to wrap my mind around the BindingList<T> and INotifyPropertChanged. More specifically - How do I make a collection of objects (having objects as properties) which will allow me to subscribe to events throughout the tree? To that end, I have examined the code offered as examples by others. One such project that I downloaded was Nested Property Binding - CodeProject by "seesharper". Now, the article explains the implementation, but there was a question by "Someone@AnotherWorld" about "INotifyPropertyChanged in nested objects". His question was: Hi, nice stuff! But after a couple of time using your solution I realize the ObjectBindingSource ignores the PropertyChanged event of nested objects. E.g. I've got a class 'Foo' with two properties named 'Name' and 'Bar'. 'Name' is a string an 'Bar' reference an instance of class 'Bar', which has a 'Name' property of type string too and both classes implements INotifyPropertyChanged. With your binding source reading and writing with both properties ('Name' and 'Bar_Name') works fine but the PropertyChanged event works only for the 'Name' property, because the binding source listen only for events of 'Foo'. One workaround is to retrigger the PropertyChanged event in the appropriate class (here 'Foo'). What's very unclean! The other approach would be to extend ObjectBindingSource so that all owner of nested property which implements INotifyPropertyChanged get used for receive changes, but how? Thanks! I had asked about BindingList<T> yesterday and received a good answer from Aaronaught. In my question, I had a similar point as "Someone@AnotherWorld": if Keywords were to implement INotifyPropertyChanged, would changes be accessible to the BindingList through the ScannedImage object? To which Aaronaught's response was: No, they will not. BindingList only looks at the specific object in the list, it has no ability to scan all dependencies and monitor everything in the graph (nor would that always be a good idea, if it were possible). I understand Aaronaught's comment regarding this behavior not necessarily being a good idea. Additionally, his suggestion to have my bound object "relay" events on behalf of it's member objects works fine and is perfectly acceptable. For me, "re-triggering" the PropertyChanged event does not seem so unclean as "Someone@AnotherWorld" laments. I do understand why he protests - in the interest of loosely coupled objects. However, I believe that coupling between objects that are part of a composition is logical and not so undesirable as this may be in other scenarios. (I am a newb, so I could be waaayyy off base.) Anyway, in the interest of exploring an answer to the question by "Someone@AnotherWorld", I altered the MainForm.cs file of the example project from Nested Property Binding - CodeProject by "seesharper" to the following: using System; using System.Collections.Generic; using System.ComponentModel; using System.Core.ComponentModel; using System.Windows.Forms; namespace ObjectBindingSourceDemo { public partial class MainForm : Form { private readonly List<Customer> _customers = new List<Customer>(); private readonly List<Product> _products = new List<Product>(); private List<Order> orders; public MainForm() { InitializeComponent(); dataGridView1.AutoGenerateColumns = false; dataGridView2.AutoGenerateColumns = false; CreateData(); } private void CreateData() { _customers.Add( new Customer(1, "Jane Wilson", new Address("98104", "6657 Sand Pointe Lane", "Seattle", "USA"))); _customers.Add( new Customer(1, "Bill Smith", new Address("94109", "5725 Glaze Drive", "San Francisco", "USA"))); _customers.Add( new Customer(1, "Samantha Brown", null)); _products.Add(new Product(1, "Keyboard", 49.99)); _products.Add(new Product(2, "Mouse", 10.99)); _products.Add(new Product(3, "PC", 599.99)); _products.Add(new Product(4, "Monitor", 299.99)); _products.Add(new Product(5, "LapTop", 799.99)); _products.Add(new Product(6, "Harddisc", 89.99)); customerBindingSource.DataSource = _customers; productBindingSource.DataSource = _products; orders = new List<Order>(); orders.Add(new Order(1, DateTime.Now, _customers[0])); orders.Add(new Order(2, DateTime.Now, _customers[1])); orders.Add(new Order(3, DateTime.Now, _customers[2])); #region Added by me OrderLine orderLine1 = new OrderLine(_products[0], 1); OrderLine orderLine2 = new OrderLine(_products[1], 3); orderLine1.PropertyChanged += new PropertyChangedEventHandler(OrderLineChanged); orderLine2.PropertyChanged += new PropertyChangedEventHandler(OrderLineChanged); orders[0].OrderLines.Add(orderLine1); orders[0].OrderLines.Add(orderLine2); #endregion // Removed by me in lieu of region above. //orders[0].OrderLines.Add(new OrderLine(_products[0], 1)); //orders[0].OrderLines.Add(new OrderLine(_products[1], 3)); ordersBindingSource.DataSource = orders; } #region Added by me // Have to wait until the form is Shown to wire up the events // for orderDetailsBindingSource. Otherwise, they are triggered // during MainForm().InitializeComponent(). private void MainForm_Shown(object sender, EventArgs e) { orderDetailsBindingSource.AddingNew += new AddingNewEventHandler(orderDetailsBindSrc_AddingNew); orderDetailsBindingSource.CurrentItemChanged += new EventHandler(orderDetailsBindSrc_CurrentItemChanged); orderDetailsBindingSource.ListChanged += new ListChangedEventHandler(orderDetailsBindSrc_ListChanged); } private void orderDetailsBindSrc_AddingNew( object sender, AddingNewEventArgs e) { } private void orderDetailsBindSrc_CurrentItemChanged( object sender, EventArgs e) { } private void orderDetailsBindSrc_ListChanged( object sender, ListChangedEventArgs e) { ObjectBindingSource bindingSource = (ObjectBindingSource)sender; if (!(bindingSource.Current == null)) { // Unsure if GetType().ToString() is required b/c ToString() // *seems* // to return the same value. if (bindingSource.Current.GetType().ToString() == "ObjectBindingSourceDemo.OrderLine") { if (e.ListChangedType == ListChangedType.ItemAdded) { // I wish that I knew of a way to determine // if the 'PropertyChanged' delegate assignment is null. // I don't like the current test, but it seems to work. if (orders[ ordersBindingSource.Position].OrderLines[ e.NewIndex].Product == null) { orders[ ordersBindingSource.Position].OrderLines[ e.NewIndex].PropertyChanged += new PropertyChangedEventHandler( OrderLineChanged); } } if (e.ListChangedType == ListChangedType.ItemDeleted) { // Will throw exception when leaving // an OrderLine row with unitialized properties. // // I presume this is because the item // has already been 'disposed' of at this point. // *but* // Will it be actually be released from memory // if the delegate assignment for PropertyChanged // was never removed??? if (orders[ ordersBindingSource.Position].OrderLines[ e.NewIndex].Product != null) { orders[ ordersBindingSource.Position].OrderLines[ e.NewIndex].PropertyChanged -= new PropertyChangedEventHandler( OrderLineChanged); } } } } } private void OrderLineChanged(object sender, PropertyChangedEventArgs e) { MessageBox.Show(e.PropertyName, "Property Changed:"); } #endregion } } In the method private void orderDetailsBindSrc_ListChanged(object sender, ListChangedEventArgs e) I am able to hook up the PropertyChangedEventHandler to the OrderLine object as it is being created. However, I cannot seem to find a way to unhook the PropertyChangedEventHandler from the OrderLine object before it is being removed from the orders[i].OrderLines list. So, my questions are: Am I simply trying to do something that is very, very wrong here? Will the OrderLines object that I add the delegate assignments to ever be released from memory if the assignment is not removed? Is there a "sane" method of achieving this scenario? Also, note that this question is not specifically related to my prior. I have actually solved the issue which had prompted me to inquire before. However, I have reached a point with this particular topic of discovery where my curiosity has exceeded my patience - hopefully someone here can shed some light on this?

    Read the article

  • winforms databinding best practices

    - by Kaiser Soze
    Demands / problems: I would like to bind multiple properties of an entity to controls in a form. Some of which are read only from time to time (according to business logic). When using an entity that implements INotifyPropertyChanged as the DataSource, every change notification refreshes all the controls bound to that data source (easy to verify - just bind two properties to two controls and invoke a change notification on one of them, you will see that both properties are hit and reevaluated). There should be user friendly error notifications (the entity implements IDataErrorInfo). (probably using ErrorProvider) Using the entity as the DataSource of the controls leads to performance issues and makes life harder when its time for a control to be read only. I thought of creating some kind of wrapper that holds the entity and a specific property so that each control would be bound to a different DataSource. Moreover, that wrapper could hold the ReadOnly indicator for that property so the control would be bound directly to that value. The wrapper could look like this: interface IPropertyWrapper : INotifyPropertyChanged, IDataErrorInfo { object Value { get; set; } bool IsReadOnly { get; } } But this means also a different ErrorProvider for each property (property wrapper) I feel like I'm trying to reinvent the wheel... What is the 'proper' way of handling complex binding demands like these? Thanks ahead.

    Read the article

  • Combobox with collection view itemssource does not update selection box item on changes to the Model

    - by Vinit Sankhe
    Hello, Sorry for the earlier lengthy post. Here is my concise (!) description. I bind a collection view to a combobox as a itemsSource and also bind its selectedvalue with a property from my view model. I must keep IsSynchronizedWithCurrentItem="False". I change the source list ofr the view and then refresh the view. The changed (added, removed, edited) items appear correctly in the item list of the combo. But problem is with the selected item. When I change its property which is also the displaymember path of the combo, the changed property value does not reflect back on the selecton box of the combo. If you open the combo dropdown it appears correctly on the item list but not on the selection box. Now if I change the combobox tag to Listbox in my XAML (keeping all attributes as it is) then when selected item's displaymember property value is updated, the changes reflect back on the selected item of the list box . Why this issue? Just FYI: My View Model has properties EmployeeCollectionView and SelectedEmployeeId which are bound to combo as ItemsSource and SelectedValue resp. This VM implements the INotifyPropertyChanged interface. My core employee class (list of which is the source for the EmployeeCollectionView) is simply a Model class without INotifyPropertyChanged. DisplayMemberPath is "Name" property of employee Model class. I change this by some means and expect the combo selection box to update the value. I tried refreshing ther SelectedEmployeeId by setting it 0 (where it correctly selects the dummy "-- Select All --" employee entry from itemsSource) and old selected value back. But no use. The old value takes me back to the old label. Items collection has latest entry though. When I make combobox's IsEditable=True before the view's refresh and after refresh I make IsEditable=False then the things work out correctly! But this is a patch and is unnecessary. Thx Vinit Sankhe

    Read the article

  • validation properties by attribute

    - by netmajor
    I create class with two property - name,link(below). I use simple property validation by Required and StringLength attribute. I bind this class object to WPF ListBox(with textBoxs). But when I have textbox empty or write words longer than 8 sign nothing happens :/ What should I do to fires ErrorMessage? Or how to implement validation in other way ? I also try use : if (value is int) { throw new ArgumentException("Wpisales stringa!!"); } But it only fires in debug mode :/ My class with implementation of attribute validation: public class RssInfo : INotifyPropertyChanged { public RssInfo() { } public RssInfo(string _nazwa, string _link) { nazwa = _nazwa; link = _link; } private string nazwa; [Required(ErrorMessage = "To pole jest obowiazkowe nAZWA")] public string Nazwa { get { return nazwa; } set { if (value != nazwa) { nazwa = value; onPropertyChanged("Nazwa"); } if (value is int) { throw new ArgumentException("Wpisales stringa!!"); } } } private string link; [Required(ErrorMessage="To pole jest obowiazkowe link")] [StringLength(8, ErrorMessage = "Link cannot be longer than 8 characters")] public string Link { get { return link; } set { if (value != link) { link = value; onPropertyChanged("Link"); } } } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; #endregion private void onPropertyChanged(string propertyName) { if (this.PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } }

    Read the article

  • Chain of DataBinding

    - by Neir0
    Hello I am trying to do follow DataBinding Property -> DependencyProperty -> Property But i have trouble. For example, We have simple class with two properties implements INotifyPropertyChanged: public class MyClass : INotifyPropertyChanged { private string _num1; public string Num1 { get { return _num1; } set { _num1 = value; OnPropertyChanged("Num1"); } } private string _num2; public string Num2 { get { return _num2; } set { _num2 = value; OnPropertyChanged("Num2"); } } public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string e) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(e)); } } And TextBlock declared in xaml: <TextBlock Name="tb" FontSize="20" Foreground="Red" Text="qwerqwerwqer" /> Now lets trying to bind Num1 to tb.Text: private MyClass _myClass = new MyClass(); public MainWindow() { InitializeComponent(); Binding binding1 = new Binding("Num1") { Source = _myClass, Mode = BindingMode.OneWay }; Binding binding2 = new Binding("Num2") { Source = _myClass, Mode = BindingMode.TwoWay }; tb.SetBinding(TextBlock.TextProperty, binding1); //tb.SetBinding(TextBlock.TextProperty, binding2); var timer = new Timer(500) {Enabled = true,}; timer.Elapsed += (sender, args) => _myClass.Num1 += "a"; timer.Start(); } It works well. But if we uncomment this string tb.SetBinding(TextBlock.TextProperty, binding2); then TextBlock display nothing. DataBinding doesn't work! How can i to do what i want?

    Read the article

  • MVVM: Thin ViewModels and Rich Models

    - by Dan Bryant
    I'm continuing to struggle with the MVVM pattern and, in attempting to create a practical design for a small/medium project, have run into a number of challenges. One of these challenges is figuring out how to get the benefits of decoupling with this pattern without creating a lot of repetitive, hard-to-maintain code. My current strategy has been to create 'rich' Model classes. They are fully aware that they will be consumed by an MVVM pattern and implement INotifyPropertyChanged, allow their collections to be observed and remain cognizant that they may always be under observation. My ViewModel classes tend to be thin, only exposing properties when data actually needs to be transformed, with the bulk of their code being RelayCommand handlers. Views happily bind to either ViewModels or Models directly, depending on whether any data transformation is required. I use AOP (via Postsharp) to ease the pain of INotifyPropertyChanged, making it easy to make all of my Model classes 'rich' in this way. Are there significant disadvantages to using this approach? Can I assume that the ViewModel and View are so tightly coupled that if I need new data transformation for the View, I can simply add it to the ViewModel as needed?

    Read the article

  • WPF Notify changes on object

    - by Erik Z
    I have a gridview were I define some columns, like this... <GridViewColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding MyProp}" /> </DataTemplate> </GridViewColumn.CellTemplate> I bind my gridview to a collection and implemts INotifyPropertyChanged in the property MyProp. This works well and any changes of MyProp are reflected to the gridview. If I add another column that is bound to the object itself I dont get any notifications/updates. My code... <GridViewColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding Converter={StaticResource myConverter}}"/> </DataTemplate> </GridViewColumn.CellTemplate> I think I need something like INotifyPropertyChanged for the object but I have no idea how to do this. Any suggestions?

    Read the article

  • ViewModel Views relation/link/syncroniztion

    - by mehran
    Third try to describing problem: Try 1: Sunchronizing view model and view Try2: WPF ViewModel not active presenter Try3: I have some class for view models: public class Node : INotifyPropertyChanged { Guid NodeId { get; set; } public string Name { get; set; } } public class Connection: INotifyPropertyChanged { public Node StartNode { get; set; } public Node EndNode { get; set; } } public class SettingsPackModel { public List<Node> Nodes { get; private set; } public List<Connection> Connections { get; private set; } } I also have some templates to displays these models: <DataTemplate DataType="{x:Type vm:Node}">…</DataTemplate> <DataTemplate DataType="{x:Type vm:Connection}"> <my:ConnectionElment StartNodeElment="???" EndNodeElment="???"> </my:ConnectionElment> <DataTemplate> But the problem is that DataTemplate for Connection need reference ot two element of type UIElement , how can I pass these two, how can I fill ??? in above expression?

    Read the article

  • Why doesn't this data binding work?

    - by Qwertie
    I have a ViewModel class that contains a list of points, and I am trying to bind it to a Polyline. The Polyline picks up the initial list of points, but does not notice when additional points are added even though I implement INotifyPropertyChanged. What's wrong? <StackPanel> <Button Click="Button_Click">Add!</Button> <Polyline x:Name="_line" Points="{Binding Pts}" Stroke="Black" StrokeThickness="5"/> </StackPanel> C# side: // code-behind _line.DataContext = new ViewModel(); private void Button_Click(object sender, RoutedEventArgs e) { // The problem is here: NOTHING HAPPENS ON-SCREEN! ((ViewModel)_line.DataContext).AddPoint(); } // ViewModel class public class ViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public PointCollection Pts { get; set; } public ViewModel() { Pts = new PointCollection(); Pts.Add(new Point(1, 1)); Pts.Add(new Point(11, 11)); } public void AddPoint() { Pts.Add(new Point(25, 13)); if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Pts")); } }

    Read the article

  • C# Cast Class to Overridden Class

    - by Nathan Tornquist
    I have a class Application that I need to override with INotifyPropertyChanged events. I have written the logic to override the original class and ended up creating SuperApplication I am pulling the data from a library though, and cannot change the loading logic. I just need a way to get the data from the original class into my superClass. I've tried things like superClass = (SuperApplication)standardClass; but it hasn't worked. How would I go about doing this? If it helps, this is the code I'm using to override the original class: public class SuperCreditApplication : CreditApplication { public SuperCreditApplicant Applicant { get; set; } public SuperCreditApplicant CoApplicant { get; set; } } public class SuperCreditApplicant : CreditApplicant { public SuperProspect Prospect { get; set; } } public class SuperProspect : Prospect, INotifyPropertyChanged { public State DriverLicenseState { get { return DriverLicenseState; } set { DriverLicenseState = value; OnPropertyChanged("DriverLicenseState"); } } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } }

    Read the article

  • Regarding the ViewModel

    - by mizipzor
    Im struggling to understand the ViewModel part of the MVVM pattern. My current approach is to have a class, with no logic whatsoever (important), except that it implements INotifyPropertyChanged. The class is just a collection of properties, a struct if you like, describing an as small part of the data as possible. I consider this my Model. Most of the WPF code I write are settings dialogs that configure said Model. The code-behind of the dialog exposes a property which returns an instance of the Model. In the XAML code I bind to subproperties of that property, thereby binding directly to the Model's properties. Which works quite well since it implements the INotifyPropertyChanged. I consider this settings dialog the View. However, I havent really been able to figure out what in all this is the ViewModel. The articles Ive read suggests that the ViewModel should tie the View and the Model together, providing the logic the Model lacks but is still to complex to go directly into the View. Is this correct? Would, in my example, the code-behind of the settings dialog be considered the ViewModel? I just feel a bit lost and would like my peers to debunk some of my assumptions. Am I completely off track here?

    Read the article

  • How can I bind to a helper property in Silverlight

    - by Matt
    For the sake of argument, here's a simple person class public class Person : DependencyObject, INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public static readonly DependencyProperty FirstNameProperty = DependencyProperty.Register( "FirstName", typeof ( string ), typeof ( Person ), null ); public static readonly DependencyProperty LastNameProperty = DependencyProperty.Register( "LastName", typeof( string ), typeof( Person ), null ); public string FirstName { get { return ( string ) GetValue( FirstNameProperty ); } set { SetValue( FirstNameProperty, value ); if(PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs( "FirstName" )); } } public string LastName { get { return ( string ) GetValue( LastNameProperty ); } set { SetValue( LastNameProperty, value ); if ( PropertyChanged != null ) PropertyChanged( this, new PropertyChangedEventArgs( "LastName" ) ); } } } I want to go about creating a readonly property like this public string FullName { get { return FirstName + " " + LastName; } } How does binding work in this scenario? I've tried adding a DependancyProperty and raised the PropertyChanged event for the fullname. Basically I just want to have a property that I can bind to that returns the fullname of a user whenever the first or last name changes. Here's the final class I'm using with the modifications. public class Person : DependencyObject, INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public static readonly DependencyProperty FirstNameProperty = DependencyProperty.Register( "FirstName", typeof ( string ), typeof ( Person ), null ); public static readonly DependencyProperty LastNameProperty = DependencyProperty.Register( "LastName", typeof( string ), typeof( Person ), null ); public static readonly DependencyProperty FullNameProperty = DependencyProperty.Register( "FullName", typeof( string ), typeof( Person ), null ); public string FirstName { get { return ( string ) GetValue( FirstNameProperty ); } set { SetValue( FirstNameProperty, value ); if ( PropertyChanged != null ) { PropertyChanged( this, new PropertyChangedEventArgs( "FirstName" ) ); PropertyChanged( this, new PropertyChangedEventArgs( "FullName" ) ); } } } public string LastName { get { return ( string ) GetValue( LastNameProperty ); } set { SetValue( LastNameProperty, value ); if ( PropertyChanged != null ) { PropertyChanged( this, new PropertyChangedEventArgs( "LastName" ) ); PropertyChanged( this, new PropertyChangedEventArgs( "FullName" ) ); } } } public string FullName { get { return GetValue( FirstNameProperty ) + " " + GetValue( LastNameProperty ); } } }

    Read the article

  • Windows Phone 7: Making ListBox items change dynamically

    - by Chad La Guardia
    I am working on creating a Windows Phone app that will play a series of sound clips selected from a list. I am using the MVVM (Model View View-Model) Design pattern and have designed a model for my data, along with a view model for my page. Here is what the XAML for the ListBox looks like: <ListBox x:Name="MediaListBox" Margin="0,0,-12,0" ItemsSource="{Binding Media}" SelectionChanged="MediaListBox_SelectionChanged" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch"> <ListBox.ItemTemplate > <DataTemplate> <StackPanel Margin="0,0,0,17" Width="432" Orientation="Horizontal"> <Image Source="../Media/Images/play.png" /> <StackPanel > <TextBlock Text="{Binding Title}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/> <TextBlock Text="{Binding ShortDescription}" TextWrapping="Wrap" Margin="12,-6,12,0" Visibility="{Binding ShortDescriptionVisibility}" Style="{StaticResource PhoneTextSubtleStyle}"/> <TextBlock Text="{Binding LongDescription}" TextWrapping="Wrap" Visibility="{Binding LongDescriptionVisibility}" /> <StackPanel> <Slider HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" Visibility="{Binding LongDescriptionVisibility}" ValueChanged="Slider_ValueChanged" LargeChange="0.25" SmallChange="0.05" /> </StackPanel> </StackPanel> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> My question is this: I want to be able to expand and collapse part of the items in the ListBox. As you can see, I have a binding for the visibility. That binding is coming from the MediaModel. However, when I change this property in the ObservableCollection, the page is not updated to reflect this. The ViewModel for this page looks like this: public class ListenPageViewModel : INotifyPropertyChanged { public ListenPageViewModel() { this.Media = new ObservableCollection<MediaModel>; } /// <summary> /// A collection for MediaModel objects. /// </summary> public ObservableCollection<MediaModel> Media { get; private set; } public bool IsDataLoaded { get; private set; } /// <summary> /// Creates and adds the media to their respective collections. /// </summary> public void LoadData() { this.Media.Clear(); this.Media.Add(new MediaModel() { Title = "Media 1", ShortDescription = "Short here.", LongDescription = "Long here.", MediaSource = "/Media/test.mp3", LongDescriptionVisibility = Visibility.Collapsed, ShortDescriptionVisibility = Visibility.Visible }); this.Media.Add(new MediaModel() { Title = "Media 2", ShortDescription = "Short here.", LongDescription = "Long here.", MediaSource = "/Media/test2.mp3", LongDescriptionVisibility = Visibility.Collapsed, ShortDescriptionVisibility = Visibility.Visible }); this.IsDataLoaded = true; } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(String propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (null != handler) { handler(this, new PropertyChangedEventArgs(propertyName)); } } } The bindings work correctly and I am seeing the data displayed; however, when I change the properties, the list does not update. I believe that this may be because when I change things inside the observable collection, the property changed event is not firing. What can I do to remedy this? I have poked around for some info on this, but many of the tutorials don't cover this kind of behavior. Any help would be greatly appreciated! Thanks Edit: As requested, I have added the MediaModel code: public class MediaModel : INotifyPropertyChanged { public string Title { get; set; } public string ShortDescription { get; set; } public string LongDescription { get; set; } public string MediaSource { get; set; } public Visibility LongDescriptionVisibility { get; set; } public Visibility ShortDescriptionVisibility { get; set; } public MediaModel() { } public MediaModel(string Title, string ShortDescription, string LongDescription, string MediaSource, Visibility LongDescriptionVisibility, Visibility ShortDescriptionVisibility) { this.Title = Title; this.ShortDescription = ShortDescription; this.LongDescription = LongDescription; this.MediaSource = MediaSource; this.LongDescriptionVisibility = LongDescriptionVisibility; this.ShortDescriptionVisibility = ShortDescriptionVisibility; } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(String propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (null != handler) { handler(this, new PropertyChangedEventArgs(propertyName)); } } } Originally, I did not have this class implement the INotifyPropertyChanged. I did this to see if it would solve the problem. I was hoping this could just be a data object.

    Read the article

  • WPF Databinding- Part 2 of 3

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

    Read the article

  • Local LINQtoSQL Database For Your Windows Phone 7 Application

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

    Read the article

  • Wpf Combobox in Master/Detail MVVM

    - by isak
    I have MVVM master /details like this: <Window.Resources> <DataTemplate DataType="{x:Type model:EveryDay}"> <views:EveryDayView/> </DataTemplate> <DataTemplate DataType="{x:Type model:EveryMonth}"> <views:EveryMonthView/> </DataTemplate> </Window.Resources> <Grid> <ListBox Margin="12,24,0,35" Name="schedules" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding Path=Elements}" SelectedItem="{Binding Path=CurrentElement}" DisplayMemberPath="Name" HorizontalAlignment="Left" Width="120"/> <ContentControl Margin="168,86,32,35" Name="contentControl1" Content="{Binding Path=CurrentElement.Schedule}" /> <ComboBox Height="23" Margin="188,24,51,0" Name="comboBox1" VerticalAlignment="Top" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding Path=Schedules}" SelectedItem="{Binding Path=CurrentElement.Schedule}" DisplayMemberPath="Name" SelectedValuePath="ID" SelectedValue="{Binding Path=CurrentElement.Schedule.ID}" /> </Grid> This Window has DataContext class: public class MainViewModel : INotifyPropertyChanged { public MainViewModel() { _elements.Add(new Element("first", new EveryDay("First EveryDay object"))); _elements.Add(new Element("second", new EveryMonth("Every Month object"))); _elements.Add(new Element("third", new EveryDay("Second EveryDay object"))); _schedules.Add(new EveryDay()); _schedules.Add(new EveryMonth()); } private ObservableCollection<ScheduleBase> _schedules = new ObservableCollection<ScheduleBase>(); public ObservableCollection<ScheduleBase> Schedules { get { return _schedules; } set { _schedules = value; this.OnPropertyChanged("Schedules"); } } private Element _currentElement = null; public Element CurrentElement { get { return this._currentElement; } set { this._currentElement = value; this.OnPropertyChanged("CurrentElement"); } } private ObservableCollection<Element> _elements = new ObservableCollection<Element>(); public ObservableCollection<Element> Elements { get { return _elements; } set { _elements = value; this.OnPropertyChanged("Elements"); } } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } #endregion } One of Views: <UserControl x:Class="Views.EveryDayView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" > <Grid > <GroupBox Header="Every Day Data" Name="groupBox1" VerticalAlignment="Top"> <Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> <TextBox Name="textBox2" Text="{Binding Path=AnyDayData}" /> </Grid> </GroupBox> </Grid> I have problem with SelectedItem in ComboBox.It doesn't works correctly.

    Read the article

  • WPF Databinding thread safety?

    - by Petoj
    Well lets say i have an object that i databind to, it implements INotifyPropertyChanged to tell the GUI when a value has changed... if i trigger this from a different thread than the GUI thread how would wpf behave? and will it make sure that it gets the value of the property from memory and not the cpu cache? more or less im asking if wpf does lock() on the object containing the property...

    Read the article

  • use Data Annotation to my Linq to SQL

    - by Khalid Omar
    i have a mvc web project and i'm using linq to sql i'm using dataannotaion like this public class ClientValidation { [Required] public string name1st { get; set; } } then in the linq class i add that above client class [global::System.Data.Linq.Mapping.TableAttribute(Name = "dbo.Client")] [MetadataType(typeof(ClientValidation))] public partial class Client : INotifyPropertyChanging, INotifyPropertyChanged { } every thing is going ok the question is when i re generate the linq when i add table or change any thing in database i need to rewrite [MetadataType(typeof(ClientValidation))] is there any other method to enable me regenerate the model and keep the data annotation as it

    Read the article

  • DatagridView loses current edit on Background update

    - by yoni.s
    Here's my problem : I have a DataGridView bound to a BindingList of custom objects. A background thread is constantly updating a value of these objects. The udpates are showing correctly, and everything is fine except for one thing - If you try to edit a different field while the background-updated field is being updated, it loses the entered value. Here is a code sample that demonstrates this behavior: (for new form, drop a new DataGridView on:) using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Threading; namespace WindowsFormsApplication2 { public partial class Form1 : Form { private BindingList<foo> flist; private Thread thrd; private BindingSource b; public Form1() { InitializeComponent(); flist = new BindingList<foo> { new foo(){a =1,b = 1, c=1}, new foo(){a =1,b = 1, c=1}, new foo(){a =1,b = 1, c=1}, new foo(){a =1,b = 1, c=1} }; b = new BindingSource(); b.DataSource = flist; dataGridView1.DataSource = b; thrd = new Thread(new ThreadStart(updPRoc)); thrd.Start(); } private void upd() { flist.ToList().ForEach(f=>f.c++); } private void updPRoc() { while (true) { this.BeginInvoke(new MethodInvoker(upd)); Thread.Sleep(1000); } } } public class foo:INotifyPropertyChanged { private int _c; public int a { get; set; } public int b { get; set; } public int c { get {return _c;} set { _c = value; if (PropertyChanged!= null) PropertyChanged(this,new PropertyChangedEventArgs("c")); } } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; #endregion } } So, you edit column a or b, you will see that the column c update causes you to lose your entry. Any thoughts appreciated.

    Read the article

  • WPF ComboBox drop-down (data bound) values not changing

    - by Jefim
    I bind the ItemsSource of a ComboBox to an ObservableCollection<MyClass>. In code I change the collection (e.g. edit the MyClass.Name property). The problem: the change is not reflected in the dropdown box if the ComboBox, yet when I seled the item from the dropdown it is displayed correctly in the selected item box of the ComboBox. What's going on? :) PS MyClass has INotifyPropertyChanged implemented

    Read the article

  • Change user control appearance based on state

    - by John
    I have a user control that consists of four overlapping items: 2 rectangles, an ellipse and a lable <UserControl x:Class="UserControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="50.1" Height="45.424" Background="Transparent" FontSize="24"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="3.303*" /> <RowDefinition Height="40*" /> <RowDefinition Height="2.121*" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="5.344*" /> <ColumnDefinition Width="40.075*" /> <ColumnDefinition Width="4.663*" /> </Grid.ColumnDefinitions> <Rectangle Name="Rectangle1" RadiusX="5" RadiusY="5" Fill="DarkGray" Grid.ColumnSpan="3" Grid.RowSpan="3" /> <Ellipse Name="ellipse1" Fill="{Binding State}" Margin="0.016,0.001,4.663,0" Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="2" Stroke="Black" IsEnabled="True" Panel.ZIndex="2" /> <Label Name="lblNumber" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Foreground="White" FontWeight="Bold" FontSize="24" Grid.Column="1" Grid.Row="1" Padding="0" Panel.ZIndex="3">9</Label> <Rectangle Grid.Column="1" Grid.Row="1" Margin="0.091,0,4.663,0" Fill="Blue" Name="rectangle2" Stroke="Black" Grid.ColumnSpan="2" Panel.ZIndex="1" /> </Grid> Here is my business object that I want to control the state of my user control: Imports System.Data Imports System.ComponentModel Public Class BusinessObject Implements INotifyPropertyChanged 'Public logger As log4net.ILog Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged Private _state As States Public Enum States State1 State2 State3 End Enum Public Property State() As States Get Return _state End Get Set(ByVal value As States) If (value <> _state) Then _state = value RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("State")) End If End Set End Property Protected Sub OnPropertyChanged(ByVal name As String) RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(name)) End Sub I want to be able to change the state of a business object in the code behind and have that change the colors of multiple shapes in my usercontrol. I'm not sure about how to do the binding. I set the datacontext of the user control in the code behind but not sure if that's right. I'm new to WPF and programming in general and I'm stuck on where to go from here. Any recommendations would be greatly appreciated!!

    Read the article

  • How to use command bindings in user controls in wpf?

    - by Sam
    In MainWindow the commandbinding works fine. In UserControl1 it doesnt work. Note the datacontext is set correctly as is evidenced by the content of the button which is the result of a binding. I am not trying to bind the command in the usercontrol to a command in mainwindow or any other such trickery. I am just trying to replicate what I did in MainWindow in UserControl1. // MainWindow xaml <StackPanel> <Button Content="Click Here" Command="{Binding ClickHereCommand}" Height="25" Width="90"></Button> <local:UserControl1></local:UserControl1> </StackPanel> // MainWindow public partial class MainWindow : Window { public static RoutedCommand ClickHereCommand { get; set; } public MainWindow() { InitializeComponent(); this.DataContext = this; ClickHereCommand = new RoutedCommand(); CommandBindings.Add(new CommandBinding(ClickHereCommand, ClickHereExecuted)); } public void ClickHereExecuted(object sender, ExecutedRoutedEventArgs e) { System.Windows.MessageBox.Show("hello"); } } // UserControl1 xaml <UserControl x:Class="CommandBindingTest.UserControl1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300" x:Name="root"> <Grid DataContext="{Binding ElementName=root}" > <Button Content="{Binding ButtonContent}" Command="{Binding ClickHereCommand}" Height="25" Width="90"></Button> </Grid> </UserControl> // UserControl1 public partial class UserControl1 : UserControl, INotifyPropertyChanged { private string _ButtonContent; public string ButtonContent { get { return _ButtonContent; } set { if (_ButtonContent != value) { _ButtonContent = value; OnPropertyChanged("ButtonContent"); } } } public static RoutedCommand ClickHereCommand { get; set; } public UserControl1() { InitializeComponent(); ClickHereCommand = new RoutedCommand(); CommandBindings.Add(new CommandBinding(ClickHereCommand, ClickHereExecuted)); ButtonContent = "Click Here"; } public void ClickHereExecuted(object sender, ExecutedRoutedEventArgs e) { System.Windows.MessageBox.Show("hello from UserControl1"); } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string name) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(name)); } } #endregion }

    Read the article

  • WPF: Problem with TreeView databinding

    - by Am
    Hi, I have a tree view defined as follows: <TreeView Grid.Row="0" Grid.Column="0" Margin="0" FlowDirection="LeftToRight" ItemTemplate="{StaticResource NavigationHeaderTemplate}" Name="TreeView2"> </TreeView> The data binding is: public class ViewTag : INotifyPropertyChanged { private string _tagName; public string TagName { get { return _tagName; } set { _tagName = value; PropertyChanged(this, new PropertyChangedEventArgs("Tag Name")); } } private ObservableCollection<ViewTag> _childTags; public ObservableCollection<ViewTag> ChildTags { get { return _childTags; } set { _childTags = value; OnPropertyChanged(new PropertyChangedEventArgs("Child Tags")); } } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(PropertyChangedEventArgs e) { if (PropertyChanged != null) PropertyChanged(this, e); } #endregion public ViewTag(string tagName, ObservableCollection<ViewTag> childTags) { _tagName = tagName; _childTags = childTags; } } And my test binding is: List<ViewTag> tempTags = new List<ViewTag>(); ViewTag t1, t2, t3, t4, t5, t6; t1 = new ViewTag("Computers", null); t2 = new ViewTag("Chemistry", null); t3 = new ViewTag("Physics", null); var t123 = new ObservableCollection<ViewTag>(); t123.Add(t1); t123.Add(t2); t123.Add(t3); t4 = new ViewTag("Science", t123); var t1234 = new ObservableCollection<ViewTag>(); t1234.Add(t4); t5 = new ViewTag("All Items", t1234); t6 = new ViewTag("Untagged", null); var tall = new ObservableCollection<ViewTag>(); tall.Add(t5); tall.Add(t6); xy.Add(new ViewNavigationTree() { Header = "Tags", Image = "img/tags2.ico", Children = tall }); var rootFolders = eDataAccessLayer.RepositoryFacrory.Instance.MonitoredDirectoriesRepository.Directories.ToList(); var viewFolders = new ObservableCollection<ViewTag>(); foreach (var vf in rootFolders) { viewFolders.Add(new ViewTag(vf.FullPath, null)); } xy.Add(new ViewNavigationTree() { Header = "Folders", Image = "img/folder_16x16.png", Children = viewFolders }); xy.Add(new ViewNavigationTree() { Header = "Authors", Image = "img/user_16x16.png", Children = null }); xy.Add(new ViewNavigationTree() { Header = "Publishers", Image = "img/powerplant_32.png", Children = null }); TreeView2.ItemsSource = xy; Problem is, the tree only shows: + Tags All Items Untagged + Folders dir 1 dir 2 ... Authors Publishers The items I added under "All Items" aren't displayed. Being a WPF nub, i can't put my finger on the problem. Any help will be greatly appriciated.

    Read the article

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