Search Results

Search found 1189 results on 48 pages for 'mvvm'.

Page 8/48 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • WPF MVVM Picklist Example

    - by Tim
    Hi, I am looking for a way of easily maintaining a list of Users belonging to a particular Group. I have thought about using a Picklist, where I have 2 listboxs, the first contains a list of Users the second a list of Users belonging to the Group. There will be buttons to allow the adding and removing of selected Users from the Group. As users are added they move from the left listbox to the right, as they are removed they are move from the right to the list. This is pretty common situation. Do you know of any examples of doing this in WPF using the MVVM pattern? I am having difficulty understand how the binding may work to my View Model and Business Entities. Especially persisting the data back to the database. I am using stored procedure calls to do the CRUD logic, so I need to keep a list of which Users had been removed so I can delete them. Is this the best way to perform this functionality or is there a better way. I simply want to pick from a list (the list may be large).

    Read the article

  • Wpf Mvvm ComboBox

    - by 2Fast4YouBR
    Hi All, I am new in the Wpf world, so I created a couple of views and all of them have at least one ComboBox, as I am using the MvvM pattern, I get my self re-typing all the time the same line of codes to fill the Combo and to get the SelectedItem (creating properties, privates for fill and other to get). Is there some kind of framework that can improve this part ? or hack/trick ??? as I see too much repetitive code... maybe I am doing something wrong, take a look: XAML: <ComboBox name= "cbDepartments" DisplayMemberPath="DepartmentName" SelectedValuePath ="PrimaryKey" ItemsSource="{Binding Path=Departments}" SelectedItem="{Binding Path=DefaultBranch,Mode=TwoWay}" > ViewModel: private Department defaultBranch; public Department DefaultBranch { get { return this.defaultBranch; } set { if (this.defaultBranch != value) { this.defaultBranch = value; this.OnPropertyChanged("DefaultBranch"); this.saveChangeCommand.RaiseCanExecuteChanged(); this.UserMessage = string.Empty; } } } private ObservableCollection<Department> departments; public ObservableCollection<Department> Departments { get { return this.departments; } set { if (this. departments!= value) { this. departments = value; this.OnPropertyChanged("Departments"); } } }

    Read the article

  • Problem Binding a ObservableCollection to a ListBox in WPF/MVVM

    - by alexqs
    I'm working in some code , using wpf and starting to use mvvm. So far i have no problem, when i have one element and I have to show the values of it in the screen (binding of the specific name of the property). But now, i have to work with a property list , not knowing the names of it. So I created a class, named GClass, that only have two propierties, name and value. I created the ObservableCollection, and fill for now with direct values, and asign the view (lstview) datacontext with the object i have created. But I cant see any result, it always shows a blank listbox. Can someone tell me if see why is happening ? Code of c# VDt = new ObservableCollection<GClass>(); var vhDt = message.SelectSingleElement(typeof (Vh)) as Vehiculo; if(vhDt != null) { VDt.Add(new GClass() {Name = "Numero: ", Value = ""}); VDt.Add(new GClass() {Name = "Marca: ", Value = ""}); VDt.Add(new GClass() {Name = "Conductor: ", Value = ""}); lstview.DataContext = this; _regionManager.RegisterViewWithRegionInIndex(RegionNames.MainRegion, lstview, 0); Code of the view <ListBox Margin="5,5,5,25" ItemsSource="{Binding VDt}"> <ListBox.Template> <ControlTemplate> <ListViewItem Content="{Binding Name}"></ListViewItem> <ListViewItem Content="{Binding Value}"></ListViewItem> </ControlTemplate> </ListBox.Template> </ListBox> I have research here, but i cant see, what I'm doing wrong. I will apreciate if someone help me.

    Read the article

  • Programatic re-evalutation of MVVM command's "can execute" state

    - by dzs
    Hello! I'm writing a WPF application using the MVVM pattern, based on the following article: WPF Apps With The Model-View-ViewModel Design Pattern I have two buttons on my View with the buttons' "Command" property bound (with data binding) to a given instance of the RelayCommand class (see "Figure 3 The RelayCommand Class" from the article above). The RelayCommand class has support for checking whether the given command can be executed. WPF automatically disables buttons whose command cannot be executed. Each of my commands (in the ViewModel class) start a background operation, and the command cannot be executed again until the background operation is finished. The RelayCommand instances have information whether the background operation is still working or it is finished. My problem is the following: after pressing the any of the buttons, the buttons automaticaly go disabled (which is OK) because the background operation started and the command cannot be executed until it is finished, but after the operation had finished, the buttons don't go enabled automatically because their command's "can be executed" predicate is not automatically reevaluated. The reevaluation can be manually triggered by having the application loose and regain focus (by pressing ALT+TAB). After doing this trick, the buttons get enabled once again. How can I programatically reevaluate the buttons' command's "can execute" state?

    Read the article

  • MVVM Light - master / child views and dependency properties

    - by Carl Dickinson
    I'm getting an odd problem when implementing a master / child view and custom dependency properties. Within my master view I'm binding the view model declaratively in the XAML as follows: DataContext="{Binding MainViewModelProperty, Source={StaticResource Locator}}" and my MainViewModel is exposing an observable collection which I'm binding to an ItemsControl as follows: <ItemsControl ItemsSource="{Binding Lists}" Height="490" Canvas.Top="10" Width="70"> <ItemsControl.ItemTemplate> <DataTemplate> <Canvas> <local:TaskListControl Canvas.Left="{Binding ListLeft}" Canvas.Top="{Binding ListTop}" Width="{Binding ListWidth}" Height="{Binding ListHeight}" ListDetails="{Binding}"/> </Canvas> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> TaskListControl in turn declares and bind to it's ViewModel and I've also defined a dependency property for the ListDetails property. The ListDetails property is not being set and if I remove the declarative reference to it's viewmodel the dependency property's callback does get fired. Is there a conflict with declaratively binding to viewmodels and definig dependency properties? I really like MVVM Light's blendability and want to perserve with this problem so any help would be apprectiated. If you'd like to receive the source for my project then please ask

    Read the article

  • Silverlight MVVM binding seems not to work

    - by Savvas Sopiadis
    Hi everybody! Building my first SL MVVM application (Silverlight4 RC) and have some issues i don't understand. Having a WPF background i don't know what is going on here: ViewModel has several properties, in which one is called SelectedRecord. This is a get only property and is defined like this: public Culture SelectedRecord { get { return culturesView.View.CurrentItem as Culture; } } As you can see it is gets the current value of a CollectionViewSource (called culturesView). So if i select a Culture, the SelectedRecord (gets a value directly from within the CollectionViewSource) as expected. (Actually there is a datagrid control bound to the CollectionViewSource, hence it is possible to change the selected item) OK. Now to the View . There are several views which access this ViewModel and in particular there is one which shows the values of the aforementioned property SelectedRecord (let's call it the EditView). To show this EditView there is a button (which has its Command property bound to an ICommand in the ViewModel) which functions (the first time) as expected. This means: 1st try : i select a record, switch to EditView, outcome: selected record values are shown (as expected!!). 2nd try: switch back to datagrid, select another record, switch to EditView, outcome: the values of the previous shown record are shown again!!! WHY?? First i thought that the SelectedRecord has not the correct value set, but i was mistaken: it HAS the correct value! So it should be shown!? What am i missing? In WPF this would work!! Thanks in advance

    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

  • MVVM using Page Navigation On Windows Mobile 7

    - by anon
    The Navigation framework in Windows Mobile 7 is a cut down version of what is in Silverlight. You can only navigate to a Uri and not pass in a view. Since the NavigationService is tied to the View, how do people get this to fit into MVVM. For example: public class ViewModel : IViewModel { private IUnityContainer container; private IView view; public ViewModel(IUnityContainer container, IView view) { this.container = container; this.view = view; } public ICommand GoToNextPageCommand { get { ... } } public IView { get { return this.view; } } public void GoToNextPage() { // What do I put here. } } public class View : PhoneApplicationPage, IView { ... public void SetModel(IViewModel model) { ... } } I am using the Unity IOC container. I have to resolve my view model first and then use the View property to get hold of the view and then show it. However using the NavigationService, I have to pass in a view Uri. There is no way for me to create the view model first. Is there a way to get around this.

    Read the article

  • MVC2 DataAnnotations on ViewModel - Don't understand using it with MVVM pattern

    - by ScottSEA
    I have an MVC2 Application that uses MVVM pattern. I am trying use Data Annotations to validate form input. In my ThingsController I have two methods: [HttpGet] public ActionResult Index() { return View(); } public ActionResult Details(ThingsViewModel tvm) { if (!ModelState.IsValid) return View(tvm); try { Query q = new Query(tvm.Query); ThingRepository repository = new ThingRepository(q); tvm.Things = repository.All(); return View(tvm); } catch (Exception) { return View(); } } My Details.aspx view is strongly typed to the ThingsViewModel: <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Config.Web.Models.ThingsViewModel>" %> The ViewModel is a class consisting of a IList of returned Thing objects and the Query string (which is submitted on the form) and has the Required data annotation: public class ThingsViewModel { public IList<Thing> Things{ get; set; } [Required(ErrorMessage="You must enter a query")] public string Query { get; set; } } When I run this, and click the submit button on the form without entering a value I get a YSOD with the following error: The model item passed into the dictionary is of type 'Config.Web.Models.ThingsViewModel', but this dictionary requires a model item of type System.Collections.Generic.IEnumerable`1[Config.Domain.Entities.Thing]'. How can I get Data Annotations to work with a ViewModel? I cannot see what I'm missing or where I'm going wrong - the VM was working just fine before I started mucking around with validation.

    Read the article

  • Silverlight MVVM Confusion: Updating Image Based on State

    - by senfo
    I'm developing a Silverlight application and I'm trying to stick to the MVVM principals, but I'm running into some problems changing the source of an image based on the state of a property in the ViewModel. For all intents and purposes, you can think of the functionality I'm implementing as a play/pause button for an audio app. When in the "Play" mode, IsActive is true in the ViewModel and the "Pause.png" image on the button should be displayed. When paused, IsActive is false in the ViewModel and "Play.png" is displayed on the button. Naturally, there are two additional images to handle when the mouse hovers over the button. I thought I could use a Style Trigger, but apparently they're not supported in Silverlight. I've been reviewing a forum post with a question similar to mine where it's suggested to use the VisualStateManager. While this might help with changing the image for hover/normal states, the part missing (or I'm not understanding) is how this would work with a state set via the view model. The post seems to apply only to events rather than properties of the view model. Having said that, I also haven't successfully completed the normal/hover affects, either. Below is my Silverlight 4 XAML. It should also probably be noted I'm working with MVVM Light. <UserControl x:Class="Foo.Bar.MyUserControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" mc:Ignorable="d" d:DesignHeight="100" d:DesignWidth="200"> <UserControl.Resources> <Style x:Key="MyButtonStyle" TargetType="Button"> <Setter Property="IsEnabled" Value="true"/> <Setter Property="IsTabStop" Value="true"/> <Setter Property="Background" Value="#FFA9A9A9"/> <Setter Property="Foreground" Value="#FF000000"/> <Setter Property="MinWidth" Value="5"/> <Setter Property="MinHeight" Value="5"/> <Setter Property="Margin" Value="0"/> <Setter Property="HorizontalAlignment" Value="Left" /> <Setter Property="HorizontalContentAlignment" Value="Center"/> <Setter Property="VerticalAlignment" Value="Top" /> <Setter Property="VerticalContentAlignment" Value="Center"/> <Setter Property="Cursor" Value="Hand"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Button"> <Grid> <Image Source="/Foo.Bar;component/Resources/Icons/Bar/Play.png"> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="Active"> <VisualState x:Name="MouseOver"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Source" Storyboard.TargetName="/Foo.Bar;component/Resources/Icons/Bar/Play_Hover.png" /> </Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> </Image> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> </UserControl.Resources> <Grid x:Name="LayoutRoot" Background="White"> <Button Style="{StaticResource MyButtonStyle}" Command="{Binding ChangeStatus}" Height="30" Width="30" /> </Grid> </UserControl> What is the proper way to update images on buttons with the state determined by the view model? Update I changed my Button to a ToggleButton hoping I could use the Checked state to differentiate between play/pause. I practically have it, but I ran into one additional problem. I need to account for two states at the same time. For example, Checked Normal/Hover and Unchecked Normal/Hover. Following is my updated XAML: <UserControl x:Class="Foo.Bar.MyUserControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" mc:Ignorable="d" d:DesignHeight="100" d:DesignWidth="200"> <UserControl.Resources> <Style x:Key="MyButtonStyle" TargetType="ToggleButton"> <Setter Property="IsEnabled" Value="true"/> <Setter Property="IsTabStop" Value="true"/> <Setter Property="Background" Value="#FFA9A9A9"/> <Setter Property="Foreground" Value="#FF000000"/> <Setter Property="MinWidth" Value="5"/> <Setter Property="MinHeight" Value="5"/> <Setter Property="Margin" Value="0"/> <Setter Property="HorizontalAlignment" Value="Left" /> <Setter Property="HorizontalContentAlignment" Value="Center"/> <Setter Property="VerticalAlignment" Value="Top" /> <Setter Property="VerticalContentAlignment" Value="Center"/> <Setter Property="Cursor" Value="Hand"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ToggleButton"> <Grid> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CommonStates"> <VisualState x:Name="Normal"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="Pause"> <DiscreteObjectKeyFrame KeyTime="0"> <DiscreteObjectKeyFrame.Value> <Visibility>Collapsed</Visibility> </DiscreteObjectKeyFrame.Value> </DiscreteObjectKeyFrame> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="MouseOver"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="PlayHover"> <DiscreteObjectKeyFrame KeyTime="0"> <DiscreteObjectKeyFrame.Value> <Visibility>Visible</Visibility> </DiscreteObjectKeyFrame.Value> </DiscreteObjectKeyFrame> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="Play"> <DiscreteObjectKeyFrame KeyTime="0"> <DiscreteObjectKeyFrame.Value> <Visibility>Collapsed</Visibility> </DiscreteObjectKeyFrame.Value> </DiscreteObjectKeyFrame> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> </VisualStateGroup> <VisualStateGroup x:Name="CheckStates"> <VisualState x:Name="Checked"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="Pause"> <DiscreteObjectKeyFrame KeyTime="0"> <DiscreteObjectKeyFrame.Value> <Visibility>Visible</Visibility> </DiscreteObjectKeyFrame.Value> </DiscreteObjectKeyFrame> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="Play"> <DiscreteObjectKeyFrame KeyTime="0"> <DiscreteObjectKeyFrame.Value> <Visibility>Collapsed</Visibility> </DiscreteObjectKeyFrame.Value> </DiscreteObjectKeyFrame> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="PlayHover"> <DiscreteObjectKeyFrame KeyTime="0"> <DiscreteObjectKeyFrame.Value> <Visibility>Collapsed</Visibility> </DiscreteObjectKeyFrame.Value> </DiscreteObjectKeyFrame> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="Unchecked" /> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <Image x:Name="Play" Source="/Foo.Bar;component/Resources/Icons/Bar/Play.png" /> <Image x:Name="Pause" Source="/Foo.Bar;component/Resources/Icons/Bar/Pause.png" Visibility="Collapsed" /> <Image x:Name="PlayHover" Source="/Foo.Bar;component/Resources/Icons/Bar/Play_Hover.png" Visibility="Collapsed" /> <Image x:Name="PauseHover" Source="/Foo.Bar;component/Resources/Icons/Bar/Pause_Hover.png" Visibility="Collapsed" /> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> </UserControl.Resources> <Grid x:Name="LayoutRoot" Background="White"> <ToggleButton Style="{StaticResource MyButtonStyle}" IsChecked="{Binding IsPlaying}" Command="{Binding ChangeStatus}" Height="30" Width="30" /> </Grid> </UserControl>

    Read the article

  • My first MVVM application architecture setup

    - by 1110
    Ok, time is coming for my first WPF project :). I work before with Flex and PureMVC and I know how project setup is important in RIA's. I decided to work with MVVM. And decided to work with PRISM framework. Application is somethin like operating system. There will be 'shell' (parent for smaller applications). Smaller application I plan to make like modules. So I plan to design structure of project something like this. Module_A {view, viewModel, model, assets} // for example calculator Module_B {view, viewModel, model, assets} // notebook etc I read prism doc and I see that parrent for all this modules should be shell project, and this is my main question here. Parrent_Project {App.xaml, Bootstrapper.cs, Shell.xaml} Because this shell will be fullscreen with background images (like operating system), right click with some features. Is that ok to create folder structure like in modulesXYZ for Shell.xaml here? I want to start project with good structure so any advice is welcome. Thanks

    Read the article

  • Applying MVVM to ASP.NET

    - by Moussa
    Hi everyone, I am learning MVVM and i want to use it with ASP.NET. Some of the examples that i found on the internet uses XAML for the view. Is there a way to use a regular ASP.NET page instead of XAML for the view? Here is a XAML example: <UserControl x:Class="MVVMExample.DetailView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Grid x:Name="LayoutRoot" Background="White" DataContext="{Binding CurrentContact}"> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition/> </Grid.ColumnDefinitions> <TextBlock Text="Name:" HorizontalAlignment="Right" Margin="5"/> <TextBlock Text="{Binding FullName}" HorizontalAlignment="Left" Margin="5" Grid.Column="1"/> <TextBlock Text="Phone:" HorizontalAlignment="Right" Margin="5" Grid.Row="1"/> <TextBlock Text="{Binding PhoneNumber}" HorizontalAlignment="Left" Margin="5" Grid.Row="1" Grid.Column="1"/> </Grid> </UserControl> Thank you for your time.

    Read the article

  • MVVM and Databinding with UniformGrid

    - by JP
    I'm trying to style the back of a WPF chart with some rectangles. I'm using MVVM, and I need the rectangles to be uniformly sized. When defined via Xaml, this works with a fixed "BucketCount" of 4: <VisualBrush> <VisualBrush.Visual> <UniformGrid Height="500" Width="500" Rows="1" Columns="{Binding BucketCount}"> <Rectangle Grid.Row="0" Grid.Column="0" Fill="#22ADD8E6" /> <Rectangle Grid.Row="0" Grid.Column="1" Fill="#22D3D3D3"/> <Rectangle Grid.Row="0" Grid.Column="2" Fill="#22ADD8E6"/> <Rectangle Grid.Row="0" Grid.Column="3" Fill="#22D3D3D3"/> </UniformGrid> </VisualBrush.Visual> <VisualBrush> How can I bind my ObservableCollection of Rectangles? There is no "ItemsSource" property on UniformGrid. Do I need to use an ItemsControl? If so, how can I do this? Thanks in advance.

    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

  • Silverlight child windows in MVVM pattern

    - by rrejc
    Hello, I am trying to find the right way to get the data from a ChildWindow/popup using a MVVM pattern in Silverlight (3). For example: I have a main page with a data entry form and I want to open a popup with a list of customers. When user selects a customer I want to transfer selected customer into the main page. This is what the (example) code which I am using at the moment: Main page public partial class MainPage : UserControl { public MainPageViewModel ViewModel { get; private set; } public MainPage() { InitializeComponent(); ViewModel = new MainPageViewModel(); DataContext = ViewModel; } private void SearchCustomer_Click(object sender, RoutedEventArgs e) { ViewModel.SearchCustomer(); } } public class MainPageViewModel: ViewModel { private string customer; public string Customer { get { return customer; } set { customer = value; RaisePropertyChanged("Customer"); } } public void SearchCustomer() { // Called from a view SearchWindow searchWindow = new SearchWindow(); searchWindow.Closed += (sender, e) => { if ((bool)searchWindow.DialogResult) { Customer = searchWindow.ViewModel.SelectedCustomer.ToString(); } }; searchWindow.Show(); } } Child window public partial class SearchWindow : ChildWindow { public SearchWindowViewModel ViewModel { get; private set; } public SearchWindow() { InitializeComponent(); ViewModel = new SearchWindowViewModel(); DataContext = ViewModel; } private void OKButton_Click(object sender, RoutedEventArgs e) { DialogResult = ViewModel.OkButtonClick(); } private void CancelButton_Click(object sender, RoutedEventArgs e) { DialogResult = ViewModel.CancelButtonClick(); } } public class SearchWindowViewModel: ViewModel { private Customer selectedCustomer; private ObservableCollection<Customer> customers; public ObservableCollection<Customer> Customers { get { return customers; } set {customers = value; RaisePropertyChanged("Customers"); } } public Customer SelectedCustomer { get { return selectedCustomer; } set { selectedCustomer = value; RaisePropertyChanged("SelectedCustomer"); } } public SearchWindowViewModel() { Customers = new ObservableCollection<Customer>(); ISearchService searchService = new FakeSearchService(); foreach (Customer customer in searchService.FindCustomers("dummy")) Customers.Add(customer); } public bool? OkButtonClick() { if (SelectedCustomer != null) return true; else return null; // show some error message before that } public bool? CancelButtonClick() { return false; } } Is this the right way or is there anything more "simple"? Cheers, Rok

    Read the article

  • MVVM Light Toolkit throws an System.IO.FileLoadException

    - by joebeazelman
    I'm running VS 2010 along with Expression Blend 4 beta. I created a MVVM Light project from the supplied templates and I get a System.IO.FileLoadException when I try to view the MainWindow.Xaml in VS 2010 designer window. The template already references System.Windows.Interactivity. Here are the details of the exception: System.IO.FileLoadException Could not load file or assembly 'System.Windows.Interactivity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. Operation is not supported. (Exception from HRESULT: 0x80131515) at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection, Boolean suppressSecurityChecks) at System.Reflection.Assembly.Load(AssemblyName assemblyRef) at MS.Internal.Package.VSIsolationProviderService.RemoteReferenceProxy.VsReflectionResolver.GetRuntimeAssembly(Assembly reflectionAssembly) at Microsoft.Windows.Design.Metadata.ReflectionMetadataContext.CachingReflectionResolver.GetRuntimeAssembly(Assembly reflectionAssembly) at Microsoft.Windows.Design.Metadata.ReflectionMetadataContext.Microsoft.Windows.Design.Metadata.IReflectionResolver.GetRuntimeAssembly(Assembly reflectionAssembly) at MS.Internal.Metadata.ClrAssembly.GetRuntimeMetadata(Object reflectionMetadata) at Microsoft.Windows.Design.Metadata.AttributeTableContainer.d_c.MoveNext() at Microsoft.Windows.Design.Metadata.AttributeTableContainer.GetAttributes(Assembly assembly, Type attributeType, Func`2 reflectionMapper) at MS.Internal.Metadata.ClrAssembly.GetAttributes(ITypeMetadata attributeType) at MS.Internal.Design.Metadata.Xaml.XamlAssembly.get_XmlNamespaceCompatibilityMappings() at Microsoft.Windows.Design.Metadata.Xaml.XamlExtensionImplementations.GetXmlNamespaceCompatibilityMappings(IAssemblyMetadata sourceAssembly) at Microsoft.Windows.Design.Metadata.Xaml.XamlExtensions.GetXmlNamespaceCompatibilityMappings(IAssemblyMetadata source) at MS.Internal.Design.Metadata.ReflectionProjectNode.BuildSubsumption() at MS.Internal.Design.Metadata.ReflectionProjectNode.SubsumingNamespace(Identifier identifier) at MS.Internal.Design.Markup.XmlElement.BuildScope(PrefixScope parentScope, IParseContext context) at MS.Internal.Design.Markup.XmlElement.ConvertToXaml(XamlElement parent, PrefixScope parentScope, IParseContext context, IMarkupSourceProvider provider) at MS.Internal.Design.DocumentModel.DocumentTrees.Markup.XamlSourceDocument.FullParse(Boolean convertToXamlWithErrors) at MS.Internal.Design.DocumentModel.DocumentTrees.Markup.XamlSourceDocument.get_RootItem() at Microsoft.Windows.Design.DocumentModel.Trees.ModifiableDocumentTree.get_ModifiableRootItem() at Microsoft.Windows.Design.DocumentModel.MarkupDocumentManagerBase.get_LoadState() at MS.Internal.Host.PersistenceSubsystem.Load() at MS.Internal.Host.Designer.Load() at MS.Internal.Designer.VSDesigner.Load() at MS.Internal.Designer.VSIsolatedDesigner.VSIsolatedView.Load() at MS.Internal.Designer.VSIsolatedDesigner.VSIsolatedDesignerFactory.Load(IsolatedView view) at MS.Internal.Host.Isolation.IsolatedDesigner.BootstrapProxy.LoadDesigner(IsolatedDesignerFactory factory, IsolatedView view) at MS.Internal.Host.Isolation.IsolatedDesigner.BootstrapProxy.LoadDesigner(IsolatedDesignerFactory factory, IsolatedView view) at MS.Internal.Host.Isolation.IsolatedDesigner.Load() at MS.Internal.Designer.DesignerPane.LoadDesignerView() System.NotSupportedException An attempt was made to load an assembly from a network location which would have caused the assembly to be sandboxed in previous versions of the .NET Framework. This release of the .NET Framework does not enable CAS policy by default, so this load may be dangerous. If this load is not intended to sandbox the assembly, please enable the loadFromRemoteSources switch. See http://go.microsoft.com/fwlink/?LinkId=155569 for more information.

    Read the article

  • Shawn Wildermuth violating MVVM in MSDN article?

    - by rasx
    This may be old news but back in March 2009, Shawn Wildermuth, his article, “Model-View-ViewModel In Silverlight 2 Apps,” has a code sample that includes DataServiceEntityBase: // COPIED FROM SILVERLIGHTCONTRIB Project for simplicity /// <summary> /// Base class for DataService Data Contract classes to implement /// base functionality that is needed like INotifyPropertyChanged. /// Add the base class in the partial class to add the implementation. /// </summary> public abstract class DataServiceEntityBase : INotifyPropertyChanged { /// <summary> /// The handler for the registrants of the interface's event /// </summary> PropertyChangedEventHandler _propertyChangedHandler; /// <summary> /// Allow inheritors to fire the event more simply. /// </summary> /// <param name="propertyName"></param> protected void FirePropertyChanged(string propertyName) { if (_propertyChangedHandler != null) { _propertyChangedHandler(this, new PropertyChangedEventArgs(propertyName)); } } #region INotifyPropertyChanged Members /// <summary> /// The interface used to notify changes on the entity. /// </summary> event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged { add { _propertyChangedHandler += value; } remove { _propertyChangedHandler -= value; } } #endregion What this class implies is that the developer intends to bind visuals directly to data (yes, a ViewModel is used but it defines an ObservableCollection of data objects). Is this design diverging too far from the guidance of MVVM? Now I can see some of the reasons why Shawn would go this way: what Shawn can do with DataServiceEntityBase is this sort of thing (which is intimate with the Entity Framework): // Partial Method to support the INotifyPropertyChanged interface public partial class Game : DataServiceEntityBase { #region Partial Method INotifyPropertyChanged Implementation // Override the Changed partial methods to implement the // INotifyPropertyChanged interface // This helps with the Model implementation to be a mostly // DataBound implementation partial void OnDeveloperChanged() { base.FirePropertyChanged("Developer"); } partial void OnGenreChanged() { base.FirePropertyChanged("Genre"); } partial void OnListPriceChanged() { base.FirePropertyChanged("ListPrice"); } partial void OnListPriceCurrencyChanged() { base.FirePropertyChanged("ListPriceCurrency"); } partial void OnPlayerInfoChanged() { base.FirePropertyChanged("PlayerInfo"); } partial void OnProductDescriptionChanged() { base.FirePropertyChanged("ProductDescription"); } partial void OnProductIDChanged() { base.FirePropertyChanged("ProductID"); } partial void OnProductImageUrlChanged() { base.FirePropertyChanged("ProductImageUrl"); } partial void OnProductNameChanged() { base.FirePropertyChanged("ProductName"); } partial void OnProductTypeIDChanged() { base.FirePropertyChanged("ProductTypeID"); } partial void OnPublisherChanged() { base.FirePropertyChanged("Publisher"); } partial void OnRatingChanged() { base.FirePropertyChanged("Rating"); } partial void OnRatingUrlChanged() { base.FirePropertyChanged("RatingUrl"); } partial void OnReleaseDateChanged() { base.FirePropertyChanged("ReleaseDate"); } partial void OnSystemNameChanged() { base.FirePropertyChanged("SystemName"); } #endregion } Of course MSDN code can seen as “toy code” for educational purposes but is anyone doing anything like this in the real world of Silverlight development?

    Read the article

  • WPF MVVM Pattern, ViewModel DataContext question

    - by orangecl4now
    I used this side to create my demo application http://windowsclient.net/learn/video.aspx?v=314683 The site was very useful in getting my started and in their example, they created a file called EmployeeRepository.cs which appears to be the source for the data. In their example, the data was hard-wired in code. So I'm trying to learn how to get the data from a data source (like a DB). In my specific case, I want to get the data from a Microsoft Access DB. (READ ONLY, So I'll only use SELECT commands). using System.Collections.Generic; using Telephone_Directory_2010.Model; namespace Telephone_Directory_2010.DataAccess { public class EmployeeRepository { readonly List<Employee> _employees; public EmployeeRepository() { if (_employees == null) { _employees = new List<Employee>(); } _employees.Add(Employee.CreateEmployee("Student One", "IT201", "Information Technology", "IT4207", "Building1", "Room650")); _employees.Add(Employee.CreateEmployee("Student Two", "IT201", "Information Technology", "IT4207", "Building1", "Room650")); _employees.Add(Employee.CreateEmployee("Student Three", "IT201", "Information Technology", "IT4207", "Building1", "Room650")); } public List<Employee> GetEmployees() { return new List<Employee>(_employees); } } } I found another example where an Access DB is used but it doesn't comply with MVVM. So I was trying to figure out how to add the DB file to the project, how to wire it up and bind it to a listbox (i'm not that far yet). Below is my modified file using System.Collections.Generic; using Telephone_Directory_2010.Model; // integrating new code with working code using Telephone_Directory_2010.telephone2010DataSetTableAdapters; using System.Windows.Data; namespace Telephone_Directory_2010.DataAccess { public class EmployeeRepository { readonly List<Employee> _employees; // start // integrating new code with working code private telephone2010DataSet.telephone2010DataTable employeeTable; private CollectionView dataView; internal CollectionView DataView { get { if (dataView == null) { dataView = (CollectionView) CollectionViewSource.GetDefaultView(this.DataContext); } return dataView; } } public EmployeeRepository() { if (_employees == null) { _employees = new List<Employee>(); } telephone2010TableAdapter employeeTableAdapter = new telephone2010TableAdapter(); employeeTable = employeeTableAdapter.GetData(); this.DataContext = employeeTable; } public List<Employee> GetEmployees() { return new List<Employee>(_employees); } } } I get the following error messages when building Error 1 'Telephone_Directory_2010.DataAccess.EmployeeRepository' does not contain a definition for 'DataContext' and no extension method 'DataContext' accepting a first argument of type 'Telephone_Directory_2010.DataAccess.EmployeeRepository' could be found (are you missing a using directive or an assembly reference?) C:\Projects\VS2010\Telephone Directory 2010\Telephone Directory 2010\DataAccess\EmployeeRepository.cs 23 90 Telephone Directory 2010

    Read the article

  • MVVM: how to set the datacontext of a user control

    - by EVA
    Hi, I'm writing an application in WPF, using the MVVm toolkit and have problems with hooking up the viewmodel and view. The model is created with ado.net entity framework. The viewmodel: public class CustomerViewModel { private Models.Customer customer; //constructor private ObservableCollection<Models.Customer> _customer = new ObservableCollection<Models.Customer>(); public ObservableCollection<Models.Customer> AllCustomers { get { return _customer; } } private Models.Customer _selectedItem; public Models.Customer SelectedItem { get { return _selectedItem; } } public void LoadCustomers() { List<Models.Customer> list = DataAccessLayer.getcustomers(); foreach (Models.Customer customer in list) { this._customer.Add(customer); } } } And the view (no code behind at the moment): <UserControl x:Class="Customers.Customer" 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" xmlns:vm ="clr-namespace:Customers.ViewModels" d:DesignHeight="300" d:DesignWidth="300" xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit" > <Grid> <toolkit:DataGrid ItemsSource="{Binding AllCustomers}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}" AutoGenerateColumns="True"> </toolkit:DataGrid> <toolkit:DataGrid ItemsSource="{Binding SelectedItem.Orders}"> </toolkit:DataGrid> </Grid> </UserControl> And dataaccesslayer class: class DataAccessLayer { public List<Customer> customers = new List<Customer>(); public static List<Customer> getcustomers() { entities db = new entities(); var customers = from c in db.Customer.Include("Orders") select c; return customers.ToList(); } } The problem is that no data is displayed simply because the data context is not set. I tried to do it in a code-behind but is did not work. I would prefer to do it in a xaml file anyway. Another problem is with the SelectedItem binding - the code is never used. Thanks for help! Regards, EV.

    Read the article

  • Keeping the DI-container usage in the composition root in Silverlight and MVVM

    - by adrian hara
    It's not quite clear to me how I can design so I keep the reference to the DI-container in the composition root for a Silverlight + MVVM application. I have the following simple usage scenario: there's a main view (perhaps a list of items) and an action to open an edit view for one single item. So the main view has to create and show the edit view when the user takes the action (e.g. clicks some button). For this I have the following code: public interface IView { IViewModel ViewModel {get; set;} } Then, for each view that I need to be able to create I have an abstract factory, like so public interface ISomeViewFactory { IView CreateView(); } This factory is then declared a dependency of the "parent" view model, like so: public class SomeParentViewModel { public SomeParentViewModel(ISomeViewFactory viewFactory) { // store it } private void OnSomeUserAction() { IView view = viewFactory.CreateView(); dialogService.ShowDialog(view); } } So all is well until here, no DI-container in sight :). Now comes the implementation of ISomeViewFactory: public class SomeViewFactory : ISomeViewFactory { public IView CreateView() { IView view = new SomeView(); view.ViewModel = ???? } } The "????" part is my problem, because the view model for the view needs to be resolved from the DI-container so it gets its dependencies injected. What I don't know is how I can do this without having a dependency to the DI-container anywhere except the composition root. One possible solution would be to have either a dependency on the view model that gets injected into the factory, like so: public class SomeViewFactory : ISomeViewFactory { public SomeViewFactory(ISomeViewModel viewModel) { // store it } public IView CreateView() { IView view = new SomeView(); view.ViewModel = viewModel; } } While this works, it has the problem that since the whole object graph is wired up "statically" (i.e. the "parent" view model will get an instance of SomeViewFactory, which will get an instance of SomeViewModel, and these will live as long as the "parent" view model lives), the injected view model implementation is stateful and if the user opens the child view twice, the second time the view model will be the same instance and have the state from before. I guess I could work around this with an "Initialize" method or something similar, but it doesn't smell quite right. Another solution might be to wrap the DI-container and have the factories depend on the wrapper, but it'd still be a DI-container "in disguise" there :) Any thoughts on this are greatly appreciated. Also, please forgive any mistakes or rule-breaking, since this is my first post on stackoverflow :) Thanks! ps: my current solution is that the factories know about the DI-container, and it's only them and the composition root that have this dependency.

    Read the article

  • Does this MSDN article violate MVVM?

    - by rasx
    This may be old news but back in March 2009, this article, “Model-View-ViewModel In Silverlight 2 Apps,” has a code sample that includes DataServiceEntityBase: // COPIED FROM SILVERLIGHTCONTRIB Project for simplicity /// <summary> /// Base class for DataService Data Contract classes to implement /// base functionality that is needed like INotifyPropertyChanged. /// Add the base class in the partial class to add the implementation. /// </summary> public abstract class DataServiceEntityBase : INotifyPropertyChanged { /// <summary> /// The handler for the registrants of the interface's event /// </summary> PropertyChangedEventHandler _propertyChangedHandler; /// <summary> /// Allow inheritors to fire the event more simply. /// </summary> /// <param name="propertyName"></param> protected void FirePropertyChanged(string propertyName) { if (_propertyChangedHandler != null) { _propertyChangedHandler(this, new PropertyChangedEventArgs(propertyName)); } } #region INotifyPropertyChanged Members /// <summary> /// The interface used to notify changes on the entity. /// </summary> event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged { add { _propertyChangedHandler += value; } remove { _propertyChangedHandler -= value; } } #endregion What this class implies is that the developer intends to bind visuals directly to data (yes, a ViewModel is used but it defines an ObservableCollection of data objects). Is this design diverging too far from the guidance of MVVM? Now I can see some of the reasons Why would we go this way: what we can do with DataServiceEntityBase is this sort of thing (which is intimate with the Entity Framework): // Partial Method to support the INotifyPropertyChanged interface public partial class Game : DataServiceEntityBase { #region Partial Method INotifyPropertyChanged Implementation // Override the Changed partial methods to implement the // INotifyPropertyChanged interface // This helps with the Model implementation to be a mostly // DataBound implementation partial void OnDeveloperChanged() { base.FirePropertyChanged("Developer"); } partial void OnGenreChanged() { base.FirePropertyChanged("Genre"); } partial void OnListPriceChanged() { base.FirePropertyChanged("ListPrice"); } partial void OnListPriceCurrencyChanged() { base.FirePropertyChanged("ListPriceCurrency"); } partial void OnPlayerInfoChanged() { base.FirePropertyChanged("PlayerInfo"); } partial void OnProductDescriptionChanged() { base.FirePropertyChanged("ProductDescription"); } partial void OnProductIDChanged() { base.FirePropertyChanged("ProductID"); } partial void OnProductImageUrlChanged() { base.FirePropertyChanged("ProductImageUrl"); } partial void OnProductNameChanged() { base.FirePropertyChanged("ProductName"); } partial void OnProductTypeIDChanged() { base.FirePropertyChanged("ProductTypeID"); } partial void OnPublisherChanged() { base.FirePropertyChanged("Publisher"); } partial void OnRatingChanged() { base.FirePropertyChanged("Rating"); } partial void OnRatingUrlChanged() { base.FirePropertyChanged("RatingUrl"); } partial void OnReleaseDateChanged() { base.FirePropertyChanged("ReleaseDate"); } partial void OnSystemNameChanged() { base.FirePropertyChanged("SystemName"); } #endregion } Of course MSDN code can seen as “toy code” for educational purposes but is anyone doing anything like this in the real world of Silverlight development?

    Read the article

  • Silverlight MVVM MEF ViewInjection

    - by silverfighter
    Hi all, since my title is buzzword compliant I hope I will get lots of answers to my question or any pointers to the right direction. OK what I usually do is have a ViewModel which contains a list of ViewModels itself. public class MasterViewModel { public ObservableCollection<DetailViewModel> DetailViewModels { get; set; } public DetailViewModel Detail { get; set; } } <ItemsControl ItemsSource="{Binding DetailViewModels}"> <ItemsControl> <ItemsPanelTemplate> <StackPanel /> </ItemsPanelTemplate> </ItemsControl> <ItemsControl.ItemTemplate> <DataTemplate> <views:DetailsView /> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> With this in mind I will now come to my questions. I read a lot of good things about MEF and also saw the dashboard sample of Glenn Block but this was not helping me enough. What I want to do is sidbar (like the windows sidebar). Sidebar = StackPanel ListItems = Gadget ButI want it MVVM style OK I have something like a contract IGadget I implemented an custom Export. [ExportGadget(GadgetType = GadgetTypes.News)] I have my NewsGadgetView.xaml (which implements IGadget) and imports the NewsGadgetViewModel and also makes itself available as ExportGadget. so far so good. With this I can create a set of gadgets. Then I have my SidbarView.xaml which imports a sidebarViewModel. and now I get lost... I thought of something like a GadgetFactory which uses PartCreator to create my Gadgets. but this would sit in my SidebarView.xaml But I want to have control over my Gadgets to add and remove them from my sidebar. So I thought about something like an ObserveableCollection... Which I bind to The GadgetHost is basicaly Grid which will dynamicaly load the Gadget.... So how would I create my sidebar containing different gadgets without knowing which Gadgets are available and have a ViewModel for the sidebar as well as for each gadget?... Thanks for any help....

    Read the article

  • MVVM: Binding radio buttons to a view model?

    - by David Veeneman
    I have been trying to bind a group of radio buttons to a view model using the IsChecked button. After reviewing other posts, it appears that the IsChecked property simply doesn't work. I have put together a short demo that reproduces the problem, which I have included below. Here is my question: Is there a straightforward and reliable way to bind radio buttons using MVVM? Thanks. Additional information: The IsChecked property doesn't work for two reasons: When a button is selected, the IsChecked properties of other buttons in the group don't get set to false. When a button is selected, its own IsChecked property does not get set after the first time the button is selected. I am guessing that the binding is getting trashed by WPF on the first click. Demo project: Here is the code and markup for a simple demo that reproduces the problem. Create a WPF project and replace the markup in Window1.xaml with the following: <Window x:Class="WpfApplication1.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" Loaded="Window_Loaded"> <StackPanel> <RadioButton Content="Button A" IsChecked="{Binding Path=ButtonAIsChecked, Mode=TwoWay}" /> <RadioButton Content="Button B" IsChecked="{Binding Path=ButtonBIsChecked, Mode=TwoWay}" /> </StackPanel> </Window> Replace the code in Window1.xaml.cs with the following code (a hack), which sets the view model: using System.Windows; namespace WpfApplication1 { /// <summary> /// Interaction logic for Window1.xaml /// </summary> public partial class Window1 : Window { public Window1() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { this.DataContext = new Window1ViewModel(); } } } Now add the following code to the project as Window1ViewModel.cs: using System.Windows; namespace WpfApplication1 { public class Window1ViewModel { private bool p_ButtonAIsChecked; /// <summary> /// Summary /// </summary> public bool ButtonAIsChecked { get { return p_ButtonAIsChecked; } set { p_ButtonAIsChecked = value; MessageBox.Show(string.Format("Button A is checked: {0}", value)); } } private bool p_ButtonBIsChecked; /// <summary> /// Summary /// </summary> public bool ButtonBIsChecked { get { return p_ButtonBIsChecked; } set { p_ButtonBIsChecked = value; MessageBox.Show(string.Format("Button B is checked: {0}", value)); } } } } To reproduce the problem, run the app and click Button A. A message box will appear, saying that Button A's IsChecked property has been set to true. Now select Button B. Another message box will appear, saying that Button B's IsChecked property has been set to true, but there is no message box indicating that Button A's IsChecked property has been set to false--the property hasn't been changed. Now click Button A again. The button will be selected in the window, but no message box will appear--the IsChecked property has not been changed. Finally, click on Button B again--same result. The IsChecked property is not updated at all for either button after the button is first clicked.

    Read the article

  • Refactoring multiple interfaces to a common interface using MVVM, MEF and Silverlight4

    - by Brian
    I am just learning MVVM with MEF and already see the benefits but I am a little confused about some implementation details. The app I am building has several Models that do the same with with different entities (WCF RIA Services exposing a Entity framework object) and I would like to avoid implementing a similar interface/model for each view I need and the following is what I have come up with though it currently doesn't work. The common interface has a new completed event for each model that implements the base model, this was the easiest way I could implement a common class as the compiler did not like casting from a child to the base type. The code as it currently sits compiles and runs but the is a null IModel being passed into the [ImportingConstructor] for the FaqViewModel class. I have a common interface (simplified for posting) defined as follows, this should look familiar to those who have seen Shawn Wildermuth's RIAXboxGames sample. public interface IModel { void GetItemsAsync(); event EventHandler<EntityResultsArgs<faq>> GetFaqsComplete; } A base method that implements the interface public class ModelBase : IModel { public virtual void GetItemsAsync() { } public virtual event EventHandler<EntityResultsArgs<faq>> GetFaqsComplete; protected void PerformQuery<T>(EntityQuery<T> qry, EventHandler<EntityResultsArgs<T>> evt) where T : Entity { Context.Load(qry, r => { if (evt == null) return; try { if (r.HasError) { evt(this, new EntityResultsArgs<T>(r.Error)); } else if (r.Entities.Count() > 0) { evt(this, new EntityResultsArgs<T>(r.Entities)); } } catch (Exception ex) { evt(this, new EntityResultsArgs<T>(ex)); } }, null); } private DomainContext _domainContext; protected DomainContext Context { get { if (_domainContext == null) { _domainContext = new DomainContext(); _domainContext.PropertyChanged += DomainContext_PropertyChanged; } return _domainContext; } } void DomainContext_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { switch (e.PropertyName) { case "IsLoading": AppMessages.IsBusyMessage.Send(_domainContext.IsLoading); break; case "IsSubmitting": AppMessages.IsBusyMessage.Send(_domainContext.IsSubmitting); break; } } } A model that implements the base model [Export(ViewModelTypes.FaqViewModel, typeof(IModel))] public class FaqModel : ModelBase { public override void GetItemsAsync() { PerformQuery(Context.GetFaqsQuery(), GetFaqsComplete); } public override event EventHandler<EntityResultsArgs<faq>> GetFaqsComplete; } A view model [PartCreationPolicy(CreationPolicy.NonShared)] [Export(ViewModelTypes.FaqViewModel)] public class FaqViewModel : MyViewModelBase { private readonly IModel _model; [ImportingConstructor] public FaqViewModel(IModel model) { _model = model; _model.GetFaqsComplete += Model_GetFaqsComplete; _model.GetItemsAsync(); // Load FAQS on creation } private IEnumerable<faq> _faqs; public IEnumerable<faq> Faqs { get { return _faqs; } private set { if (value == _faqs) return; _faqs = value; RaisePropertyChanged("Faqs"); } } private faq _currentFaq; public faq CurrentFaq { get { return _currentFaq; } set { if (value == _currentFaq) return; _currentFaq = value; RaisePropertyChanged("CurrentFaq"); } } public void GetFaqsAsync() { _model.GetItemsAsync(); } void Model_GetFaqsComplete(object sender, EntityResultsArgs<faq> e) { if (e.Error != null) { ErrorMessage = e.Error.Message; } else { Faqs = e.Results; } } } And then finally the Silverlight view itself public partial class FrequentlyAskedQuestions { public FrequentlyAskedQuestions() { InitializeComponent(); if (!ViewModelBase.IsInDesignModeStatic) { // Use MEF To load the View Model CompositionInitializer.SatisfyImports(this); } } [Import(ViewModelTypes.FaqViewModel)] public object ViewModel { set { DataContext = value; } } }

    Read the article

  • MvvmLight EventToCommand and WPFToolkit DataGrid double-click

    - by Tom
    Trying to figure out how to use EventToCommand to set a datagrid double click handler for rows. The command lives in the viewmodel for each row. Just that much out of my experience, since I haven't used interactions yet. Thanks. I would have used mvvmlight tag, but I don't have high enough rep yet to make new tags.

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >