Search Results

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

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

  • Business entity: private instance VS single instance

    - by taoufik
    Suppose my WinForms application has a business entity Order, the entity is used in multiple views, each view handles a different domain or use-case in the application. As an example, one managing orders, the other one digging into one order and displaying additional data. If I'd use nHibernate (or any other ORM) and use one session/dataContext per view (or per db action), I'd end up getting two different instances for the same Order (let's say orderId = 1). Although functionally the same entity, they are technically two different instances. Yes, I could implement Equals/GetHashcode to make them "seem" the same. Why would you go for a single instance per entity vs private instances per view or per use-case? Having single instances has the advantage of sharing INotifyPropertyChanged events, and sharing additional (non-persistent) data. Having a private instance in each view would give you the flexibility of the undo functionality on a view level. In the example above, I'd allow the user to change order details, and give them the flexibility to not save the change. Here, synchronisation between the view/use-case happens on a data persistence level. What would your argument be?

    Read the article

  • What's the order of execution when using IDataErrorInfo?

    - by Benny Jobigan
    Many times with WPF, we use INotifyPropertyChanged and IDataErrorInfo to enable binding and validation on our data objects. I've got a lot of properties that look like this: public SomeObject SomeData { get { return _SomeData; } set { _SomeData = value; OnPropertyChanged("SomeData"); } } Of course, I have an appropriate overridden IDataErrorInfo.this[] in my class to do validation. Question 1) In a binding situation, what happens? For example: User enters new data. Binding writes data to property. Property set method is executed. Binding checks this[] for validation. If the data is invalid, the binding sets the property back to the old value. Property set method is executed again. This is important if you are adding "hooks" into the set method, like: public string PathToFile { get { return _PathToFile; } set { if (_PathToFile != value && // prevent unnecessary actions OnPathToFileChanging(value)) // allow subclasses to do something or stop the setter { _PathToFile = value; OnPathToFileChanged(); // allow subclasses to do something afterwards OnPropertyChanged("PathToFile"); } } }

    Read the article

  • MVVM pattern: ViewModel updates after Model server roundtrip

    - by Pavel Savara
    I have stateless services and anemic domain objects on server side. Model between server and client is POCO DTO. The client should become MVVM. The model could be graph of about 100 instances of 20 different classes. The client editor contains diverse tab-pages all of them live-connected to model/viewmodel. My problem is how to propagate changes after server round-trip nice way. It's quite easy to propagate changes from ViewModel to DTO. For way back it would be possible to throw away old DTO and replace it whole with new one, but it will cause lot of redrawing for lists/DataTemplates. I could gather the server side changes and transmit them to client side. But the names of fields changed would be domain/DTO specific, not ViewModel specific. And the mapping seems nontrivial to me. If I should do it imperative way after round-trip, it would break SOC/modularity of viewModels. I'm thinking about some kind of mapping rule engine, something like automappper or emit mapper. But it solves just very plain use-cases. I don't see how it would map/propagate/convert adding items to list or removal. How to identify instances in collections so it could merge values to existing instances. As well it should propagate validation/error info. Maybe I should implement INotifyPropertyChanged on DTO and try to replay server side events on it ? And then bind ViewModel to it ? Would binding solve the problems with collection merges nice way ? Is EventAgregator from PRISM useful for that ? Is there any event record-replay component ? Is there better client side pattern for architecture with server side logic ?

    Read the article

  • Problems with "global" exception handlers for unhandled exceptions in multithreaded WPF

    - by JustABill
    I have a program that, among other things, needs to be able to refresh the contents of a directory when the user tells it to. The actual task doesn't really matter, but this is the simplest way of causing this problem to occur that I know of. If I tell it to open a directory that doesn't exist, I get the "unhandled exception" dialog in VS with a stack trace of, from outer to inner: [External code] Textbox PreviewKeyUp event [External code] ClassA's path property being set ClassA's internal path update function being called A call to the INotifyPropertyChanged event [External code] A call to the getter for ClassB's list of children A call to ClassB's internal directory list function And then it fails inside this internal function. I have the following in my App.xaml.cs: private void Application_Startup(object sender, StartupEventArgs e) { AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); Application.Current.Dispatcher.UnhandledException += new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(Dispatcher_UnhandledException); } But neither of their exception handlers are being called. If I run this program from outside VS, I don't get notified of an exception at all, it just breaks because of the invalid input. And yes, the Application_Startup event is being called. How can I properly "trap" this exception so I can provide a friendly error message and kill the program?

    Read the article

  • Suppressing PostSharp Multicast with Attribute

    - by Dan Bryant
    I've recently started experimenting with PostSharp and I found a particularly helpful aspect to automate implementation of INotifyPropertyChanged. You can see the example here. The basic functionality is excellent (all properties will be notified), but there are cases where I might want to suppress notification. For instance, I might know that a particular property is set once in the constructor and will never change again. As such, there is no need to emit the code for NotifyPropertyChanged. The overhead is minimal when classes are not frequently instantiated and I can prevent the problem by switching from an automatically generated property to a field-backed property and writing to the field. However, as I'm learning this new tool, it would be helpful to know if there is a way to tag a property with an attribute to suppress the code generation. I'd like to be able to do something like this: [NotifyPropertyChanged] public class MyClass { public double SomeValue { get; set; } public double ModifiedValue { get; private set; } [SuppressNotify] public double OnlySetOnce { get; private set; } public MyClass() { OnlySetOnce = 1.0; } }

    Read the article

  • WPF binding problem

    - by xine
    I've got some bindings in UI: <Window x:Class="Tester.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="377" Width="562" xmlns:my="clr-namespace:MyApp"> <Grid> <TextBlock Text="{Binding Path=current.Text}" Name="Text1" /> <TextBlock Text="{Binding Path=current.o.Text}" Name="Text2" /> </Grid> </Window> Code: class Coordinator : INotifyPropertyChanged{ List<Myclass1> list; int currId = 0; public Myclass1 current{ return list[currId]; } public int CurrId { get { return currId; } set { currId = value; this.PropertyChanged(this,new PropertyChangedEventArgs("current")); } } class Myclass1{ public string Text{get;} public Myclass2 o{get;} } class Myclass2{ public string Text{get;} } When currId changes Tex1 in UI changes too,but Text2 doesn't. I'm assuming this happens because Text2's source isn't updated. Does anyone know how to fix it?

    Read the article

  • WPF View/ViewModels using Generics- how?

    - by Investor5555
    New to WPF, so please bear with me... Suppose I have 2 tables in SQL Thing OtherThing Both have the exact same fields: ID (int) Name (string) Description (string) IsActive (bit/bool) DateModified (DateTime) So, I want to create one Model (not two) and do something like this: BaseModel<T>() { public int ID {get;set;} ... } etc. (of course, using the INotifyPropertyChanged, just trying to keep the code simple). I want to be able to create a BaseView and BaseViewModel that would work with whatever model conforms to the Thing/OtherThing. I am really at a loss as to what to do here to make this generic, so I don't have to have a ThingView/ThingViewModel and a OtherThingView/OtherThingViewModel... It seems that this should be simple, but I cannot seem to figure it out. Does anyone have a code example where they could interchange various items from a dropdown list using one view, one ViewModel, and one base datamodel (and switching out the type from a dropdown)? For example, a combobox has 3 identical table structures for Thing OtherThing SomeThing and on selection changed, I want to pull the data from whatever table was selected, to be able to do standard CRUD operations on any of these 3 tables, without having to create concrete classes for each view/viewmodel.

    Read the article

  • Editing list properties using DataGridview

    - by toom
    Ok, I have my custom class: public class FileItem : INotifyPropertyChanged { int id=0; string value=""; public int Id { get { return id; } set { id = value; Changed("Id"); } } public string Value { get { return value; } set { this.value = value; Changed("Value"); } } public event PropertyChangedEventHandler PropertyChanged; void Changed(string name) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(name)); } } public BindingList<FileItem> FilesystemEntries = new BindingList<FileItem>(); And I have DatagridView1 with DataSource set to FilesystemEntries: binding.DataSource = FilesystemEntries; Already I can Add and remove rows - these chnages are reflected on collection. However, Value and Id are not saved into bidning list when i change them in DataGridView, id is always 0 and value is "". How can I make this work? Do I need to implement some interface to FileItem to allow editing properties? ReadOnly of DGV is set to false, same to all columns. Editing, Deleting and Changing are enabled.

    Read the article

  • Silverlight Data Binding for Collection in Stack Panel

    - by Blake Blackwell
    I'm new to Silverlight, so I don't have a complete grasp of all the controls at my disposal. What I would like to do is use databinding and a view model to maintain a collection of items. Here is some mock code for what I'd like to do: Model public class MyItem { public string DisplayText { get; set; } public bool Enabled { get; set; } } ViewModel public class MyViewModel : INotifyPropertyChanged { private ObservableCollection<MyItem> _myItems = new ObservableCollection<MyItem>(); public ObservableCollection<MyItem> MyItems { get { return _myItems; } set { _myItems = value NotifyPropertyChanged(this, "MyItems"); } } } View <Grid x:Name="LayoutRoot" Background="White"> <StackPanel ItemsSource="{Binding MyItems}"> <StackPanel Orientation="Horizontal"> <CheckBox "{Binding Enabled, Mode=TwoWay}"></CheckBox> <TextBlock Text="{Binding DisplayText, Mode=TwoWay}" /> </StackPanel> </StackPanel> </Grid> So my end goal would be that every time I add another MyItem to the MyItems collection it would create a new StackPanel with checkbox and textblock. I don't have to use a stack panel but just thought I'd use that for this sample.

    Read the article

  • Refreshing Read-Only (Chained) Property in MVVM

    - by Wonko the Sane
    I'm thinking this should be easy, but I can't seem to figure this out. Take these properties from an example ViewModel (ObservableViewModel implements INotifyPropertyChanged): class NameViewModel : ObservableViewModel { Boolean mShowFullName = false; string mFirstName = "Wonko"; string mLastName = "DeSane"; private readonly DelegateCommand mToggleName; public NameViewModel() { mToggleName = new DelegateCommand(() => ShowFullName = !mShowFullName); } public ICommand ToggleNameCommand { get { return mToggleName; } } public Boolean ShowFullName { get { return mShowFullName; } set { SetPropertyValue("ShowFullName", ref mShowFullName, value); } } public string Name { get { return (mShowFullName ? this.FullName : this.Initials); } } public string FullName { get { return mFirstName + " " + mLastName; } } public string Initials { get { return mFirstName.Substring(0, 1) + "." + mLastName.Substring(0, 1) + "."; } } } The guts of such a [insert your adjective here] View using this ViewModel might look like: <TextBlock x:Name="txtName" Grid.Row="0" Text="{Binding Name}" /> <Button x:Name="btnToggleName" Command="{Binding ToggleNameCommand}" Content="Toggle Name" Grid.Row="1" /> The problem I am seeing is when the ToggleNameCommand is fired. The ShowFullName property is properly updated by the command, but the Name binding is never updated in the View. What am I missing? How can I force the binding to update? Do I need to implement the Name properties as DependencyProperties (and therefore derive from DependencyObject)? Seems a little heavyweight to me, and I'm hoping for a simpler solution. Thanks, wTs

    Read the article

  • WPF validation on Enter Key Up

    - by Martin
    I'm trying to validate a UI change when Enter key is pressed. The UI element is a textbox, which is data binded to a string. My problem is that the data binding hasn't updated TestText when Enter key is Up. It is only updated when I press the button which brings up a message box. /// <summary> /// Interaction logic for Window1.xaml /// </summary> public partial class Window1 : Window, INotifyPropertyChanged { String _testText = new StringBuilder("One").ToString(); public string TestText { get { return _testText; } set { if (value != _testText) { _testText = value; OnPropertyChanged("TestText"); } } } public Window1() { InitializeComponent(); myGrid.DataContext = this; } private void OnPropertyChanged(string property) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(property)); } } public event PropertyChangedEventHandler PropertyChanged; private void onKeyUp(object sender, KeyEventArgs e) { if (e.Key != System.Windows.Input.Key.Enter) return; System.Diagnostics.Trace.WriteLine(TestText); } private void button1_Click(object sender, RoutedEventArgs e) { MessageBox.Show(TestText); } } Window XAML: Window x:Class="VerificationTest.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300" KeyUp="onKeyUp" TextBox XAML: TextBox Name="myTextBox" Text="{Binding TestText}" Button XAML: Button Name="button1" Click="button1_Click"

    Read the article

  • wpf observableCollection

    - by Asha
    I have an ObservableCollection which is dataContext for my treeview when I try to remove an Item from ObservableCollection I will get an error that Object reference not set to an instance of an object . can you please tell me why this error is happening and what is the solution thanks EDIT 1: The code is something like : class MyClass : INotifyPropertyChanged { //my class code here } public partial class UC_myUserControl : UserControl { private ObservableCollection<MyClass> myCollection = new ObservableCollection<MyClass>(); private void UserControl_Loaded(object sender, RoutedEventArgs e) { myCollection.add(new myClass); myTreeView.DataContext = myCollection ; } private void deleteItem() { myCollection.RemoveAt(0); //after removing I get error Which I guess should be something related //to interface update but I don't know how can I solve it } } Exception Detail : System.NullReferenceException was unhandled Message="Object reference not set to an instance of an object." Source="PresentationFramework" EDIT 3: I have a style which is for my treeitem to keep the treeitems expanded <Style TargetType="TreeViewItem"> <Setter Property="IsExpanded" Value="True" /> </Style> and with commenting this part I wont get any error !!! Now I want to change my question to why having this style is causing error ?

    Read the article

  • What's the order of execution in property setters when using IDataErrorInfo?

    - by Benny Jobigan
    Situation: Many times with WPF, we use INotifyPropertyChanged and IDataErrorInfo to enable binding and validation on our data objects. I've got a lot of properties that look like this: public SomeObject SomeData { get { return _SomeData; } set { _SomeData = value; OnPropertyChanged("SomeData"); } } Of course, I have an appropriate overridden IDataErrorInfo.this[] in my class to do validation. Question: In a binding situation, when does the validation code get executed? When is the property set? When is the setter code executed? What if the validation fails? For example: User enters new data. Binding writes data to property. Property set method is executed. Binding checks this[] for validation. If the data is invalid, the binding sets the property back to the old value. Property set method is executed again. This is important if you are adding "hooks" into the set method, like: public string PathToFile { get { return _PathToFile; } set { if (_PathToFile != value && // prevent unnecessary actions OnPathToFileChanging(value)) // allow subclasses to do something or stop the setter { _PathToFile = value; OnPathToFileChanged(); // allow subclasses to do something afterwards OnPropertyChanged("PathToFile"); } } }

    Read the article

  • How to get the coordinates of an image mouse click in the event handler?

    - by Edward Tanguay
    In the following WPF app, I have an Image in a ContentControl. When the user clicks on the image, how can I get the x/y coordinates of where the mouse clicked on the image? XAML: <Window x:Class="TestClick828374.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <StackPanel Margin="10"> <ContentControl Content="{Binding TheImage}" MouseDown="ContentControl_MouseDown"/> </StackPanel> </Window> Code-Behind: using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Imaging; using System.ComponentModel; namespace TestClick828374 { public partial class Window1 : Window, INotifyPropertyChanged { #region ViewModelProperty: TheImage private Image _theImage; public Image TheImage { get { return _theImage; } set { _theImage = value; OnPropertyChanged("TheImage"); } } #endregion public Window1() { InitializeComponent(); DataContext = this; TheImage = new Image(); TheImage.Source = new BitmapImage(new Uri(@"c:\test\rectangle.png")); TheImage.Stretch = Stretch.None; TheImage.HorizontalAlignment = HorizontalAlignment.Left; } #region INotifiedProperty Block public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } #endregion private void ContentControl_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e) { //how to get the coordinates of the mouse click here on the image? } } }

    Read the article

  • How can I implement an interface member in protected ?

    - by Nicolas Dorier
    Hi, I've been quite surprise when I saw the metadata of ReadOnlyObservableCollection in VS 2008... public class ReadOnlyObservableCollection<T> : ReadOnlyCollection<T>, INotifyCollectionChanged, INotifyPropertyChanged { // Summary: // Initializes a new instance of the System.Collections.ObjectModel.ReadOnlyObservableCollection<T> // class that serves as a wrapper for the specified System.Collections.ObjectModel.ObservableCollection<T>. // // Parameters: // list: // The collection to wrap. public ReadOnlyObservableCollection(ObservableCollection<T> list); // Summary: // Occurs when an item is added or removed. protected virtual event NotifyCollectionChangedEventHandler CollectionChanged; // // Summary: // Occurs when a property value changes. protected virtual event PropertyChangedEventHandler PropertyChanged; // Summary: // Raises the System.Collections.ObjectModel.ReadOnlyObservableCollection<T>.CollectionChanged // event. // // Parameters: // args: // The event data. protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs args); // // Summary: // Raises the System.Collections.ObjectModel.ReadOnlyObservableCollection<T>.PropertyChanged // event. // // Parameters: // args: // The event data. protected virtual void OnPropertyChanged(PropertyChangedEventArgs args); } As you can see, CollectionChanged, a member of INotifyCollectionChanged is implemented in protected... and I can't do that in my own class. .NET framework should not compile ! Does someone has an explanation of this mystery ?

    Read the article

  • .Net lambda expression-- where did this parameter come from?

    - by larryq
    I'm a lambda newbie, so if I'm missing vital information in my description please tell me. I'll keep the example as simple as possible. I'm going over someone else's code and they have one class inheriting from another. Here's the derived class first, along with the lambda expression I'm having trouble understanding: class SampleViewModel : ViewModelBase { private ICustomerStorage storage = ModelFactory<ICustomerStorage>.Create(); public ICustomer CurrentCustomer { get { return (ICustomer)GetValue(CurrentCustomerProperty); } set { SetValue(CurrentCustomerProperty, value); } } private int quantitySaved; public int QuantitySaved { get { return quantitySaved; } set { if (quantitySaved != value) { quantitySaved = value; NotifyPropertyChanged(p => QuantitySaved); //where does 'p' come from? } } } public static readonly DependencyProperty CurrentCustomerProperty; static SampleViewModel() { CurrentCustomerProperty = DependencyProperty.Register("CurrentCustomer", typeof(ICustomer), typeof(SampleViewModel), new UIPropertyMetadata(ModelFactory<ICustomer>.Create())); } //more method definitions follow.. Note the call to NotifyPropertyChanged(p => QuantitySaved) bit above. I don't understand where the "p" is coming from. Here's the base class: public abstract class ViewModelBase : DependencyObject, INotifyPropertyChanged, IXtremeMvvmViewModel { public event PropertyChangedEventHandler PropertyChanged; protected virtual void NotifyPropertyChanged<T>(Expression<Func<ViewModelBase, T>> property) { MvvmHelper.NotifyPropertyChanged(property, PropertyChanged); } } There's a lot in there that's not germane to the question I'm sure, but I wanted to err on the side of inclusiveness. The problem is, I don't understand where the 'p' parameter is coming from, and how the compiler knows to (evidently?) fill in a type value of ViewModelBase from thin air? For fun I changed the code from 'p' to 'this', since SampleViewModel inherits from ViewModelBase, but I was met with a series of compiler errors, the first one of which statedInvalid expression term '=>' This confused me a bit since I thought that would work. Can anyone explain what's happening here?

    Read the article

  • DataGridView update datasource directly after changed Checkbox value

    - by SchlaWiener
    I have a System.Windows.Forms DataGridView that is bound to a List<MyObject>. The class MyObject contains a boolean property that is bound to DataGridViewCheckboxCell within the DataGridView. public class MyObject { public decimal DefaultValue {get; set; } public bool HasCustomValue {get;set; } public decimal CustomValue {get;set; } public decimal CurrentValue { get { return HasCustomValue ? CustomValue : DefaultValue; } } If I change the value of HasCustomValue another (readonly) property CurrentValue changes it's value, too. That is done by implementing the INotifyPropertyChanged event (I left that part in the source example for simplicity) If I changed HasCustomValue from outside the DataGridView, the column bound to CurrentValue gets updated immediately. Howevery, If the users enables/disables the checkbox, HasCustomValue is not changed in the underlying datasource unless he leaves the column by clicking with the mouse or pressing the TAB key. Is there a way to force the grid to update the datasource directly after changing a checkbox value? If I bind a Control Property I have the ability to set the DataSourceUpdateMode to Windows.Forms.DataSourceUpdateMode.OnPropertyChanged but I haven't found anything like that in a DataGridView

    Read the article

  • Silverlight Image Data Binding

    - by Alexander
    I am new to Silverlight, and have an issue with binding. I have a class ItemsManager, that has inside its scope another class Item. class ItemsManager { ... class Item : INotifyPropertyChanged { ... private BitmapImage bitmapSource; public BitmapImage BitmapSource { get { return bitmapSource; } set { bitmapSource = value; if(PropertyChanged != null )PropertyChanged("BitmapSource") } } } } I do the following in code to test binding: { ItemsManager.Instance.AddItem("123"); //Items manager started downloading item visual //part (in my case bitmap image png) Binding b = new Binding("Source"); b.Source = ItemsManager.Instance.GetItem("123").BitmapSource; b.BindsDirectlyToSource = true; Image img = new Image(); img.SetBinding(Image.SourceProperty, b); img.Width = (double)100.0; img.Height = (double)100.0; LayoutRoot.Children.Add(img); } Once image is loaded, image doesn't appear. Though, if I set directly after image has been loaded its source, it displays well. I also noticed that PropertyChanged("BitmapSource") never fires, because PropertyChanged is null, like Image never binded to it. I am looking forward to hearing from you!

    Read the article

  • Bing Maps - Auto update location binding of pushpins

    - by abp
    Hi I'm using the Bing Maps control to display a series of custom pushpins, representing objects which are constantly moving around and changing state. Using databinding the various properties for the objects are being updated as they should, but for some reason this doesn't apply to their locations. I have the map bound to an ObservableCollection as such: <UserControl.Resources> <DataTemplate x:Key="PushpinTemplate"> <v:CustomPushpin /> </DataTemplate> </UserControl.Resources> ... <m:Map Name="map"> <m:MapItemsControl ItemTemplate="{StaticResource PushpinTemplate}" ItemsSource="{Binding Objects}" /> </m:Map> ...and in CustomPushpin: <UserControl ... m:MapLayer.Position="{Binding Location}" m:MapLayer.PositionOrigin="BottomCenter" mc:Ignorable="d" d:DesignHeight="126" d:DesignWidth="85"> Like all other properties, the Location of the individual objects are implemented using INotifyPropertyChanged. private Location _location; public Location Location { get { return _location; } set { _location = value; OnPropertyChanged("Location"); } } When the map is moving, either because of panning or zooming, the objects move, but othersize not. I can't quite figure if I'm doing something wrong here, or if it's a problem with the Bing Maps control. Any thought?

    Read the article

  • DataTrigger not reevaluating after property changes

    - by frozen
    I have a listbox which has its itemssource (this is done in the code behind on as the window is created) databound to an observable collection. The List box then has the following data template assigned against the items: usercontrol.xaml ... <ListBox x:Name="communicatorListPhoneControls" ItemContainerStyle="{StaticResource templateForCalls}"/> ... app.xaml ... <Style x:Key="templateForCalls" TargetType="{x:Type ListBoxItem}"> <Setter Property="ContentTemplate" Value="{StaticResource templateRinging}"/> <Style.Triggers> <DataTrigger Binding="{Binding Path=hasBeenAnswered}" Value="True"> <Setter Property="ContentTemplate" Value="{StaticResource templateAnswered}"/> </DataTrigger> </Style.Triggers> </Style> ... When the observable collection is updated with an object, this appears in the listbox with the correct initial datatemplate, however when the "hasBeenAnswered" property is set to true (when debugging i can see the collection is correct) the datatrigger does not re-evaluate and then update the listbox to use the correct data template. I have implemented the INotifyPropertyChanged Event in my object, and if in the template i bind to a value, i can see the value update. Its just that the datatrigger will not re-evaluate and change to the correct template. I know the datatrigger binding is correct because if i close the window and open it again, it will correctly apply the second datatemplate, because the "hasBeenAnswered" is set to True.

    Read the article

  • Problems with binding to Window Height and Width

    - by D.H.
    I have some problems when I try to bind the height and width of a window to properties in my view model. Here is a small sample app to illustrate the problem. This is the code in app.xaml.xs public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); MainWindow mainWindow = new MainWindow(); MainWindowViewModel mainWindowViewModel = new MainWindowViewModel(); mainWindow.DataContext = mainWindowViewModel; mainWindow.Show(); } } This is MainWindow.xaml: <Window x:Class="TestApp.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Height="{Binding WindowHeight}" Width="{Binding WindowWidth}" BorderThickness="{Binding WindowBorderThickness}"> </Window> And this is the view model: public class MainWindowViewModel { public int WindowWidth { get { return 100; } } public int WindowHeight { get { return 200; } } public int WindowBorderThickness { get { return 8; } } } When the program is started the getters of WindowHeight and WindowBorderThickness (but not WindowWidth) are called, so the height and the border of the window is set properly, but not the width. I then add button that will trigger PropertyChanged for all properties, so that the view model now looks like this: public class MainWindowViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public void TriggerPropertyChanges() { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("WindowWidth")); PropertyChanged(this, new PropertyChangedEventArgs("WindowHeight")); PropertyChanged(this, new PropertyChangedEventArgs("WindowBorderThickness")); } } public ICommand ButtonCommand { get { return new RelayCommand(delegate { TriggerPropertyChanges(); }); } } public int WindowWidth { get { return 100; } } public int WindowHeight { get { return 200; } } public int WindowBorderThickness { get { return 8; } } } Now, when I click the button, the getter of WindowBorderThickness is called, but not the ones for WindowWidth and WindowHeight. It all just seems very weird and inconsistent to me. What am I missing?

    Read the article

  • C# MVVM Calculating Total

    - by LnDCobra
    I need to calculate a trade value based on the selected price and quantity. How can The following is my ViewModel: class ViewModel : ViewModelBase { public Trade Trade { get { return _trade; } set { SetField(ref _trade, value, () => Trade); } } private Trade _trade; public decimal TradeValue { get { return Trade.Amount * Trade.Price; } } } ViewModelBase inherits INotifyPropertyChanged and contains SetField() The Following is the Trade class: public class Trade : INotifyPropertyChaged { public virtual Decimal Amount { get { return _amount; } set { SetField(ref _amount, value, () => Amount); } } private Decimal _amount; public virtual Decimal Price { get { return _price; } set { SetField(ref _price, value, () => Price); } } private Decimal _price; ...... } I know due to the design my TradeValue only gets calculated once (when its first requested) and UI doesn't get updated when amount/price changes. What is the best way of achieving this? Any help greatly appreciated.

    Read the article

  • Binding a single array cell to a WPF control

    - by yomi
    Hi, I have a bool array of size 4 and I want to bind each cell to a different control. This bool array represents 4 statuses (false = failure, true = success). This bool array is a propery with a class: class foo : INotifyPropertyChanged { ... private bool[] _Statuses; public bool[] Statuses { get {return Statuses;} set { Statuses = value; OnPropertyChanged("Statuses"); } } In XAML there are 4 controls, each one bound to one cell of the array: ... Text="{Binding Path=Statuses[0]}" ... ... Text="{Binding Path=Statuses[1]}" ... ... Text="{Binding Path=Statuses[2]}" ... ... Text="{Binding Path=Statuses[3]}" ... The problem is that the notify event is raised only when I change the array itself and isn't raised when I change one value within the array, i.e, next code line raises the event: Statuses = new bool[4]; but next line does not raises the event: Statuses [0] = true; How can I raise the event each time one cell is changed?

    Read the article

  • Workarounds for supporting MVVM in the Silverlight TreeView Control

    - by cibrax
    MVVM (Model-View-ViewModel) is the pattern that you will typically choose for building testable user interfaces either in WPF or Silverlight. This pattern basically relies on the data binding support in those two technologies for mapping an existing model class (the view model) to the different parts of the UI or view. Unfortunately, MVVM was not threated as first citizen for some of controls released out of the box in the Silverlight runtime or the Silverlight toolkit. That means that using data binding for implementing MVVM is not always something trivial and usually requires some customization in the existing controls. In ran into different problems myself trying to fully support data binding in controls like the tree view or the context menu or things like drag & drop.  For that reason, I decided to write this post to show how the tree view control or the tree view items can be customized to support data binding in many of its properties. In first place, you will typically use a tree view for showing hierarchical data so the view model somehow must reflect that hierarchy. An easy way to implement hierarchy in a model is to use a base item element like this one, public abstract class TreeItemModel { public abstract IEnumerable<TreeItemModel> Children; } You can later derive your concrete model classes from that base class. For example, public class CustomerModel { public string FullName { get; set; } public string Address { get; set; } public IEnumerable<OrderModel> Orders { get; set; } }   public class CustomerTreeItemModel : TreeItemModel { public CustomerTreeItemModel(CustomerModel customer) { }   public override IEnumerable<TreeItemModel> Children { get { // Return orders } } } The Children property in the CustomerTreeItem model implementation can return for instance an ObservableCollection<TreeItemModel> with the orders, so the tree view will automatically subscribe to all the changes in the collection. You can bind this model to the tree view control in the UI by using a Hierarchical data template. <e:TreeView x:Name="TreeView" ItemsSource="{Binding Customers}"> <e:TreeView.ItemTemplate> <sdk:HierarchicalDataTemplate ItemsSource="{Binding Children}"> <!-- TEMPLATE --> </sdk:HierarchicalDataTemplate> </e:TreeView.ItemTemplate> </e:TreeView> An interesting behavior with the Children property and the Hierarchical data template is that the Children property is only invoked before the expansion, so you can use lazy load at this point (The tree view control will not expand the whole tree in the first expansion). The problem with using MVVM in this control is that you can not bind properties in model with specific properties of the TreeView item such as IsSelected or IsExpanded. Here is where you need to customize the existing tree view control to support data binding in tree items. public class CustomTreeView : TreeView { public CustomTreeView() { }   protected override DependencyObject GetContainerForItemOverride() { CustomTreeViewItem tvi = new CustomTreeViewItem(); Binding expandedBinding = new Binding("IsExpanded"); expandedBinding.Mode = BindingMode.TwoWay; tvi.SetBinding(CustomTreeViewItem.IsExpandedProperty, expandedBinding); Binding selectedBinding = new Binding("IsSelected"); selectedBinding.Mode = BindingMode.TwoWay; tvi.SetBinding(CustomTreeViewItem.IsSelectedProperty, selectedBinding); return tvi; } }   public class CustomTreeViewItem : TreeViewItem { public CustomTreeViewItem() { }   protected override DependencyObject GetContainerForItemOverride() { CustomTreeViewItem tvi = new CustomTreeViewItem(); Binding expandedBinding = new Binding("IsExpanded"); expandedBinding.Mode = BindingMode.TwoWay; tvi.SetBinding(CustomTreeViewItem.IsExpandedProperty, expandedBinding); Binding selectedBinding = new Binding("IsSelected"); selectedBinding.Mode = BindingMode.TwoWay; tvi.SetBinding(CustomTreeViewItem.IsSelectedProperty, selectedBinding); return tvi; } } You basically need to derive the TreeView and TreeViewItem controls to manually add a binding for the properties you need. In the example above, I am adding a binding for the “IsExpanded” and “IsSelected” properties in the items. The model for the tree items now needs to be extended to support those properties as well, public abstract class TreeItemModel : INotifyPropertyChanged { bool isExpanded = false; bool isSelected = false;   public abstract IEnumerable<TreeItemModel> Children { get; }   public bool IsExpanded { get { return isExpanded; } set { isExpanded = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("IsExpanded")); } }   public bool IsSelected { get { return isSelected; } set { isSelected = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("IsSelected")); } }   public event PropertyChangedEventHandler PropertyChanged; } However, as soon as you use this custom tree view control, you lose all the automatic styles from the built-in toolkit themes because they are tied to the control type (TreeView in this case).  The only ugly workaround I found so far for this problem is to copy the styles from the Toolkit source code and reuse them in the application.

    Read the article

  • MVVM Light V4 preview 2 (BL0015) #mvvmlight

    - by Laurent Bugnion
    Over the past few weeks, I have worked hard on a few new features for MVVM Light V4. Here is a second early preview (consider this pre-alpha if you wish). The features are unit-tested, but I am now looking for feedback and there might be bugs! Bug correction: Messenger.CleanupList is now thread safe This was an annoying bug that is now corrected: In some circumstances, an exception could be thrown when the Messenger’s recipients list was cleaned up (i.e. the “dead” instances were removed). The method is called now and then and the exception was thrown apparently at random. In fact it was really a multi-threading issue, which is now corrected. Bug correction: AllowPartiallyTrustedCallers prevents EventToCommand to work This is a particularly annoying regression bug that was introduced in BL0014. In order to allow MVVM Light to work in XBAPs too, I added the AllowPartiallyTrustedCallers attribute to the assemblies. However, we just found out that this causes issues when using EventToCommand. In order to allow EventToCommand to continue working, I reverted to the previous state by removing the AllowPartiallyTrustedCallers attribute for now. I will work with my friends at Microsoft to try and find a solution. Stay tuned. Bug correction: XML documentation file is now generated in Release configuration The XML documentation file was not generated for the Release configuration. This was a simple flag in the project file that I had forgotten to set. This is corrected now. Applying EventToCommand to non-FrameworkElements This feature has been requested in order to be able to execute a command when a Storyboard is completed. I implemented this, but unfortunately found out that EventToCommand can only be added to Storyboards in Silverlight 3 and Silverlight 4, but not in WPF or in Windows Phone 7. This obviously limits the usefulness of this change, but I decided to publish it anyway, because it is pretty damn useful in Silverlight… Why not in WPF? In WPF, Storyboards added to a resource dictionary are frozen. This is a feature of WPF which allows to optimize certain objects for performance: By freezing them, it is a contract where we say “this object will not be modified anymore, so do your perf optimization on them without worrying too much”. Unfortunately, adding a Trigger (such as EventTrigger) to an object in resources does not work if this object is frozen… and unfortunately, there is no way to tell WPF not to freeze the Storyboard in the resources… so there is no way around that (at least none I can see. In Silverlight, objects are not frozen, so an EventTrigger can be added without problems. Why not in WP7? In Windows Phone 7, there is a totally different issue: Adding a Trigger can only be done to a FrameworkElement, which Storyboard is not. Here I think that we might see a change in a future version of the framework, so maybe this small trick will work in the future. Workaround? Since you cannot use the EventToCommand on a Storyboard in WPF and in WP7, the workaround is pretty obvious: Handle the Completed event in the code behind, and call the Command from there on the ViewModel. This object can be obtained by casting the DataContext to the ViewModel type. This means that the View needs to know about the ViewModel, but I never had issues with that anyway. New class: NotifyPropertyChanged Sometimes when you implement a model object (for example Customer), you would like to have it implement INotifyPropertyChanged, but without having all the frills of a ViewModelBase. A new class named NotifyPropertyChanged allows you to do that. This class is a simple implementation of INotifyPropertyChaned (with all the overloads of RaisePropertyChanged that were implemented in BL0014). In fact, ViewModelBase inherits NotifyPropertyChanged. ViewModelBase does not implement IDisposable anymore The IDisposable interface and the Dispose method had been marked obsolete in the ViewModelBase class already in V3. Now they have been removed. Note: By this, I do not mean that IDisposable is a bad interface, or that it shouldn’t be used on viewmodels. In the contrary, I know that this interface is very useful in certain circumstances. However, I think that having it by default on every instance of ViewModelBase was sending a wrong message. This interface has a strong meaning in .NET: After Dispose has been executed, the instance should not be used anymore, and should be ready for garbage collection. What I really wanted to have on ViewModelBase was rather a simple cleanup method, something that can be executed now and then during runtime. This is fulfilled by the ICleanup interface and its Cleanup method. If your ViewModels need IDisposable, you can still use it! You will just have to implement the interface on the class itself, because it is not available on ViewModelBase anymore. What’s next? I have a couple exciting new features implemented already but that need more testing before they go live… Just stay tuned and by MIX11 (12-14 April 2011), we should see at least a major addition to MVVM Light Toolkit, as well as another smaller feature which is pretty cool nonetheless More about this later! Happy Coding Laurent   Laurent Bugnion (GalaSoft) Subscribe | Twitter | Facebook | Flickr | LinkedIn

    Read the article

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