Search Results

Search found 895 results on 36 pages for 'viewmodel'.

Page 32/36 | < Previous Page | 28 29 30 31 32 33 34 35 36  | Next Page >

  • 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

  • Kendo UI Mobile with Knockout for Master-Detail Views

    - by Steve Michelotti
    Lately I’ve been playing with Kendo UI Mobile to build iPhone apps. It’s similar to jQuery Mobile in that they are both HTML5/JavaScript based frameworks for buildings mobile apps. The primary thing that drew me to investigate Kendo UI was its innate ability to adaptively render a native looking app based on detecting the device it’s currently running on. In other words, it will render to look like a native iPhone app if it’s running on an iPhone and it will render to look like a native Droid app if it’s running on a Droid. This is in contrast to jQuery Mobile which looks the same on all devices and, therefore, it can never quite look native for whatever device it’s running on. My first impressions of Kendo UI were great. Using HTML5 data-* attributes to define “roles” for UI elements is easy, the rendering looked great, and the basic navigation was simple and intuitive. However, I ran into major confusion when trying to figure out how to “correctly” build master-detail views. Since I was already very family with KnockoutJS, I set out to use that framework in conjunction with Kendo UI Mobile to build the following simple scenario: I wanted to have a simple “Task Manager” application where my first screen just showed a list of tasks like this:   Then clicking on a specific task would navigate to a detail screen that would show all details of the specific task that was selected:   Basic navigation between views in Kendo UI is simple. The href of an <a> tag just needs to specify a hash tag followed by the ID of the view to navigate to as shown in this jsFiddle (notice the href of the <a> tag matches the id of the second view):   Direct link to jsFiddle: here. That is all well and good but the problem I encountered was: how to pass data between the views? Specifically, I need the detail view to display all the details of whichever task was selected. If I was doing this with my typical technique with KnockoutJS, I know exactly what I would do. First I would create a view model that had my collection of tasks and a property for the currently selected task like this: 1: function ViewModel() { 2: var self = this; 3: self.tasks = ko.observableArray(data); 4: self.selectedTask = ko.observable(null); 5: } Then I would bind my list of tasks to the unordered list - I would attach a “click” handler to each item (each <li> in the unordered list) so that it would select the “selectedTask” for the view model. The problem I found is this approach simply wouldn’t work for Kendo UI Mobile. It completely ignored the click handlers that I was trying to attach to the <a> tags – it just wanted to look at the href (at least that’s what I observed). But if I can’t intercept this, then *how* can I pass data or any context to the next view? The only thing I was able to find in the Kendo documentation is that you can pass query string arguments on the view name you’re specifying in the href. This enabled me to do the following: Specify the task ID in each href – something like this: <a href=”#taskDetail?id=3></a> Attach an “init method” (via the “data-show” attribute on the details view) that runs whenever the view is activated Inside this “init method”, grab the task ID passed from the query string to look up the item from my view model’s list of tasks in order to set the selected task I was able to get all that working with about 20 lines of JavaScript as shown in this jsFiddle. If you click on the Results tab, you can navigate between views and see the the detail screen is correctly binding to the selected item:   Direct link to jsFiddle: here.   With all that being done, I was very happy to get it working with the behavior I wanted. However, I have no idea if that is the “correct” way to do it or if there is a “better” way to do it. I know that Kendo UI comes with its own data binding framework but my preference is to be able to use (the well-documented) KnockoutJS since I’m already familiar with that framework rather than having to learn yet another new framework. While I think my solution above is probably “acceptable”, there are still a couple of things that bug me about it. First, it seems odd that I have to loop through my items to *find* my selected item based on the ID that was passed on the query string - normally, with Knockout I can just refer directly to my selected item from where it was used. Second, it didn’t feel exactly right that I had to rely on the “data-show” method of the details view to set my context – normally with Knockout, I could just attach a click handler to the <a> tag that was actually clicked by the user in order to set the “selected item.” I’m not sure if I’m being too picky. I know there are many people that have *way* more expertise in Kendo UI compared to me – I’d be curious to know if there are better ways to achieve the same results.

    Read the article

  • [Windows 8] An application bar toggle button

    - by Benjamin Roux
    To stay in the application bar stuff, here’s another useful control which enable to create an application bar button that can be toggled between two different contents/styles/commands (used to create a favorite/unfavorite or a play/pause button for example). namespace Indeed.Controls { public class AppBarToggleButton : Button { public bool IsChecked { get { return (bool)GetValue(IsCheckedProperty); } set { SetValue(IsCheckedProperty, value); } } public static readonly DependencyProperty IsCheckedProperty = DependencyProperty.Register("IsChecked", typeof(bool), typeof(AppBarToggleButton), new PropertyMetadata(false, (o, e) => (o as AppBarToggleButton).IsCheckedChanged())); public string CheckedContent { get { return (string)GetValue(CheckedContentProperty); } set { SetValue(CheckedContentProperty, value); } } public static readonly DependencyProperty CheckedContentProperty = DependencyProperty.Register("CheckedContent", typeof(string), typeof(AppBarToggleButton), null); public ICommand CheckedCommand { get { return (ICommand)GetValue(CheckedCommandProperty); } set { SetValue(CheckedCommandProperty, value); } } public static readonly DependencyProperty CheckedCommandProperty = DependencyProperty.Register("CheckedCommand", typeof(ICommand), typeof(AppBarToggleButton), null); public Style CheckedStyle { get { return (Style)GetValue(CheckedStyleProperty); } set { SetValue(CheckedStyleProperty, value); } } public static readonly DependencyProperty CheckedStyleProperty = DependencyProperty.Register("CheckedStyle", typeof(Style), typeof(AppBarToggleButton), null); public bool AutoToggle { get { return (bool)GetValue(AutoToggleProperty); } set { SetValue(AutoToggleProperty, value); } } public static readonly DependencyProperty AutoToggleProperty = DependencyProperty.Register("AutoToggle", typeof(bool), typeof(AppBarToggleButton), null); private object content; private ICommand command; private Style style; private void IsCheckedChanged() { if (IsChecked) { // backup the current content and command content = Content; command = Command; style = Style; if (CheckedStyle == null) Content = CheckedContent; else Style = CheckedStyle; Command = CheckedCommand; } else { if (CheckedStyle == null) Content = content; else Style = style; Command = command; } } protected override void OnTapped(Windows.UI.Xaml.Input.TappedRoutedEventArgs e) { base.OnTapped(e); if (AutoToggle) IsChecked = !IsChecked; } } } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } To use it, it’s very simple. <ic:AppBarToggleButton Style="{StaticResource PlayAppBarButtonStyle}" CheckedStyle="{StaticResource PauseAppBarButtonStyle}" Command="{Binding Path=PlayCommand}" CheckedCommand="{Binding Path=PauseCommand}" IsChecked="{Binding Path=IsPlaying}" /> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } When the IsPlaying property (in my ViewModel) is true the button becomes a Pause button, when it’s false it becomes a Play button. Warning: Just make sure that the IsChecked property is set in last in your control !! If you don’t use style you can alternatively use Content and CheckedContent. Furthermore you can set the AutoToggle to true if you don’t want to control is IsChecked property through binding. With this control and the AppBarPopupButton, you can now create awesome application bar for your apps ! Stay tuned for more awesome Windows 8 tricks !

    Read the article

  • Silverlight Reporting Application Part 3.5 - Prism Background and WCF RIA [Series Intermission]

    Taking a step back before I dive into the details and full-on coding fun, I wanted to once again respond to a comment on my last post to clear up some things in regards to how I'm setting up my project and some of the choices I've made. Aka, thanks Ben. :) Prism Project Setup For starters, I'm not the ideal use case for a Prism application. In most cases where you've got a one-man team, Prism can be overkill as it is more intended for large teams who are geographically dispersed or in applications that have a larger scale than my Recruiting application in which you'll greatly benefit from modularity, delayed loading of xaps, etc. What Prism offers, though, is a manner for handling UI, commands, and events with the idea that, through a modular approach in which no parts really need to know about one another, I can update this application bit by bit as hiring needs change or requirements differ between offices without having to worry that changing something in the Jobs module will break something in, say, the Scheduling module. All that being said, here's a look at how our project breakdown for Recruit (MVVM/Prism implementation) looks: This could be a little misleading though, as each of those modules is actually another project in the overall Recruit solution. As far as what the projects actually are, that looks a bit like this: Recruiting Solution Recruit (Shell up there) - Main Silverlight Application .Web - Default .Web application to host the Silverlight app Infrastructure - Silverlight Class Library Project Modules - Silverlight Class Library Projects Infrastructure &Modules The Infrastructure project is probably something you'll see to some degree in any composite application. In this application, it is going to contain custom commands (you'll see the joy of these in a post or two down the road), events, helper classes, and any custom classes I need to share between different modules. Think of this as a handy little crossroad between any parts of your application. Modules on the other hand are the bread and butter of this application. Besides the shell, which holds the UI skeleton, and the infrastructure, which holds all those shared goodies, the modules are self-contained bundles of functionality to handle different concerns. In my scenario, I need a way to look up and edit Jobs, Applicants, and Schedule interviews, a Notification module to handle telling the user when different things are happening (i.e., loading from database), and a Menu to control interaction and moving between different views. All modules are going to follow the following pattern: The module class will inherit from IModule and handle initialization and loading the correct view into the correct region, whereas the Views and ViewModels folders will contain paired Silverlight user controls and ViewModel class backings. WCF RIA Services Since we've got all the projects in a single solution, we did not have to go the route of creating a WCR RIA Services Class Library. Every module has it's WCF RIA link back to the main .Web project, so the single Linq-2-SQL (yes, I said Linq-2-SQL, but I'll soon be switching to OpenAccess due to the new visual designer) context I'm using there works nicely with the scope of my project. If I were going for completely separating this project out and doing different, dynamically loaded elements, I'd probably go for the separate class library. Hope that clears that up. In the future though, I will be using that in a project that I've got in the "when I've got enough time to work on this" pipeline, so we'll get into that eventually- and hopefully when WCF RIA is in full release! Why Not use Silverlight Navigation/Business Template? The short answer- I'm a creature of habit, and having used Silverlight for a few years now, I'm used to doing lots of things manually. :) Plus, starting with a blank slate of a project I'm able to set up things exactly as I want them to be. In this case, rather than the navigation frame we would see in one of the templates, the MainRegion/ContentControl is working as our main navigation window. In many cases I will use theSilverlight navigation template to start things off, however in this case I did not need those features so I opted out of using that. Next time when I actually hit post #4, we're going to get into the modules and starting to get functionality into this application. Next week is also release week for the Q1 2010 release, so be sure to check out our annualWebinar Week (I might be biased, but Wednesday is my favorite out of the group). Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • When is my View too smart?

    - by Kyle Burns
    In this posting, I will discuss the motivation behind keeping View code as thin as possible when using patterns such as MVC, MVVM, and MVP.  Once the motivation is identified, I will examine some ways to determine whether a View contains logic that belongs in another part of the application.  While the concepts that I will discuss are applicable to most any pattern which favors a thin View, any concrete examples that I present will center on ASP.NET MVC. Design patterns that include a Model, a View, and other components such as a Controller, ViewModel, or Presenter are not new to application development.  These patterns have, in fact, been around since the early days of building applications with graphical interfaces.  The reason that these patterns emerged is simple – the code running closest to the user tends to be littered with logic and library calls that center around implementation details of showing and manipulating user interface widgets and when this type of code is interspersed with application domain logic it becomes difficult to understand and much more difficult to adequately test.  By removing domain logic from the View, we ensure that the View has a single responsibility of drawing the screen which, in turn, makes our application easier to understand and maintain. I was recently asked to take a look at an ASP.NET MVC View because the developer reviewing it thought that it possibly had too much going on in the view.  I looked at the .CSHTML file and the first thing that occurred to me was that it began with 40 lines of code declaring member variables and performing the necessary calculations to populate these variables, which were later either output directly to the page or used to control some conditional rendering action (such as adding a class name to an HTML element or not rendering another element at all).  This exhibited both of what I consider the primary heuristics (or code smells) indicating that the View is too smart: Member variables – in general, variables in View code are an indication that the Model to which the View is being bound is not sufficient for the needs of the View and that the View has had to augment that Model.  Notable exceptions to this guideline include variables used to hold information specifically related to rendering (such as a dynamically determined CSS class name or the depth within a recursive structure for indentation purposes) and variables which are used to facilitate looping through collections while binding. Arithmetic – as with member variables, the presence of arithmetic operators within View code are an indication that the Model servicing the View is insufficient for its needs.  For example, if the Model represents a line item in a sales order, it might seem perfectly natural to “normalize” the Model by storing the quantity and unit price in the Model and multiply these within the View to show the line total.  While this does seem natural, it introduces a business rule to the View code and makes it impossible to test that the rounding of the result meets the requirement of the business without executing the View.  Within View code, arithmetic should only be used for activities such as incrementing loop counters and calculating element widths. In addition to the two characteristics of a “Smart View” that I’ve discussed already, this View also exhibited another heuristic that commonly indicates to me the need to refactor a View and make it a bit less smart.  That characteristic is the existence of Boolean logic that either does not work directly with properties of the Model or works with too many properties of the Model.  Consider the following code and consider how logic that does not work directly with properties of the Model is just another form of the “member variable” heuristic covered earlier: @if(DateTime.Now.Hour < 12) {     <div>Good Morning!</div> } else {     <div>Greetings</div> } This code performs business logic to determine whether it is morning.  A possible refactoring would be to add an IsMorning property to the Model, but in this particular case there is enough similarity between the branches that the entire branching structure could be collapsed by adding a Greeting property to the Model and using it similarly to the following: <div>@Model.Greeting</div> Now let’s look at some complex logic around multiple Model properties: @if (ModelPageNumber + Model.NumbersToDisplay == Model.PageCount         || (Model.PageCount != Model.CurrentPage             && !Model.DisplayValues.Contains(Model.PageCount))) {     <div>There's more to see!</div> } In this scenario, not only is the View code difficult to read (you shouldn’t have to play “human compiler” to determine the purpose of the code), but it also complex enough to be at risk for logical errors that cannot be detected without executing the View.  Conditional logic that requires more than a single logical operator should be looked at more closely to determine whether the condition should be evaluated elsewhere and exposed as a single property of the Model.  Moving the logic above outside of the View and exposing a new Model property would simplify the View code to: @if(Model.HasMoreToSee) {     <div>There’s more to see!</div> } In this posting I have briefly discussed some of the more prominent heuristics that indicate a need to push code from the View into other pieces of the application.  You should now be able to recognize these symptoms when building or maintaining Views (or the Models that support them) in your applications.

    Read the article

  • Silverlight Relay Commands

    - by George Evjen
    v\:* {behavior:url(#default#VML);} o\:* {behavior:url(#default#VML);} w\:* {behavior:url(#default#VML);} .shape {behavior:url(#default#VML);} Normal 0 false false false false EN-US X-NONE X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin:0in; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi;} I am fairly new at Silverlight development and I usually have an issue that needs research every day. Which I enjoy, since I like the idea of going into a day knowing that I am  going to learn something new. The issue that I am currently working on centers around relay commands. I have a pretty good handle on Relay Commands and how we use them within our applications. <Button Command="{Binding ButtonCommand}" CommandParameter="NewRecruit" Content="New Recruit" /> Here in our xaml we have a button. The button has a Command and a CommandParameter. The command binds to the ButtonCommand that we have in our ViewModel RelayCommand _buttonCommand;         /// <summary>         /// Gets the button command.         /// </summary>         /// <value>The button command.</value>         public RelayCommand ButtonCommand         {             get             {                 if (_buttonCommand == null)                 {                     _buttonCommand = new RelayCommand(                         x => x != null && x.ToString().Length > 0 && CheckCommandAvailable(x.ToString()),                         x => ExecuteCommand(x.ToString()));                 }                 return _buttonCommand;             }         }   In our relay command we then do some checks with a lambda expression. We check if the command  parameter is null, is the length greater than 0 and we have a CheckCommandAvailable method that will tell  us if the button is even enabled. After we check on these three items we then pass the command parameter to an action method. This is all pretty straight forward, the issue that we solved a few days ago centered around having a control that needed to use a Relay Command and this control was a nested control and was using a different DataContext. The example below illustrates how we handled this scenario. In our xaml usercontrol we had to set a name to this control. <Controls3:RadTileViewItem x:Class="RecruitStatusTileView"     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:Controls1="clr-namespace:Telerik.Windows.Controls;assembly=Telerik.Windows.Controls"      xmlns:Controls2="clr-namespace:Telerik.Windows.Controls;assembly=Telerik.Windows.Controls.Input"      xmlns:Controls3="clr-namespace:Telerik.Windows.Controls;assembly=Telerik.Windows.Controls.Navigation"      mc:Ignorable="d" d:DesignHeight="400" d:DesignWidth="800" Header="{Binding Title,Mode=TwoWay}" MinimizedHeight="100"                             x:Name="StatusView"> Here we are using a telerik RadTileViewItem. We set the name of this control to “StatusView”. In our button control we set our command parameters and commands different than the example above. <HyperlinkButton Content="{Binding BigBoardButtonText, Mode=TwoWay}" CommandParameter="{Binding 'Position.PositionName'}" Command="{Binding ElementName=StatusView, Path=DataContext.BigBoardCommand, Mode=TwoWay}" /> This hyperlink button lives in a ListBox control and this listbox has an ItemSource of PositionSelectors. The Command Parameter is binding to the Position.Position property of that PositionSelectors object. This again is pretty straight forward again. What gets a bit tricky is the Command property in the hyperlink. It is binding to the element name we created in the user control (StatusView) Because this hyperlink is in a listbox and is in the item template it doesn’t have a direct handle on the DataContext that the RadTileViewItem has so we have to make sure it does. We do that by binding to the element name of status view then set the path to DataContext.BigBoardCommand. BigBoardCommand is the name of the RelayCommand in the view model. private RelayCommand _bigBoardCommand = null;         /// <summary>         /// Gets the big board command.         /// </summary>         /// <value>The big board command.</value>         public RelayCommand BigBoardCommand         {             get             {                 if (_bigBoardCommand == null)                 {                     _bigBoardCommand = new RelayCommand(x => true, x => AddToBigBoard(x.ToString()));                 }                 return _bigBoardCommand;             }         } From there we check for true again and then call the action and pass in the parameter that we had as the command parameter. What we are working on now is a bit trickier than this second example. In the above example we are only creating this TileViewItem with this name “StatusView” once. In another part of our application we are generating multiple TileViewItems, so we cannot set the name in the control as we cant have multiple controls with the same name. When we run the application we get an error that reads that the value is out of expected range. My searching has led me to think we cannot have multiple controls with the same name. This is today’s problem and Ill post the solution to this once it is found.

    Read the article

  • Silverlight 4 WCF RIA Services and MVVM is not as simple

    - by Thomas Jaskula
    [Disclaimer: I'm ASP.NET MVC Developer] Hi, I'm looking for some best practices with implementing MVVM pattern with WCF RIA in Silverlight 4. I'm not looking to use MEF of IoC for locating my ViewModels. What I would like to know is how to apply MVVM pattern with Silverlight 4 and WCF RIA. I don't want to use other stuff like Prism or MVVM Light toolkit. I found many examples on Internet showing how it is wonderful to drag and drop a datasource on the view and the job is done (it reminds me about my first VB6 developments). I tried to implement MVVM with WCF RIA and it's not strightforward at all. If I understand, the MVVM should contain all the logic in order to unit test it in isolation but when it comes to combine it with WCF RIA it's another story. I have the following questions. Can I use a generated metadata as model ? It would be easier to use it that if I write all from the scratch. As I saw the only way I could get data is through DomainContext or through direct binding in the view (local ressource). I don't want the direct binding in the view, not testable at all. On the other hand I can't use DomainContext, it doesn't expose any single entity !!! All I have is the EntitySet that I can bind to datagrid. How do I bind a single Entity to the DataForm from the ViewModel ? How do I udpate the model to the database ? How do I navigate from one Entity to a collection of it's itemps. For example if I have a Company Entity I would like to show a DataFrom to update a entite informations and a datagrid to show companies adresses. When saving a form would like to save information to Company and for example an information avout which adress was selected as active. Please help me understand how to do it well. Or maybe I should drop the WCF RIA and to do it with WCF from scratch ? What do you think ?

    Read the article

  • CheckBox Command Behaviors for Silverlight MVVM Pattern

    - by Blake Blackwell
    I am trying to detect when an item is checked, and which item is checked in a ListBox using Silverlight 4 and the Prism framework. I found this example on creating behaviors, and tried to follow it but nothing is happening in the debugger. I have three questions: Why isn't my command executing? How do I determine which item was checked (i.e. pass a command parameter)? How do I debug this? (i.e. where can I put break points to begin stepping into this) Here is my code: View: <ListBox x:Name="MyListBox" ItemsSource="{Binding PanelItems, Mode=TwoWay}"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <CheckBox IsChecked="{Binding Enabled}" my:Checked.Command="{Binding Check}" /> <TextBlock x:Name="DisplayName" Text="{Binding DisplayName}"/> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> ViewModel: public MainPageViewModel() { _panelItems.Add( new PanelItem { Enabled = true, DisplayName = "Test1" } ); Check = new DelegateCommand<object>( itemChecked ); } public void itemChecked( object o ) { //do some stuff } public DelegateCommand<object> Check { get; set; } Behavior Class public class CheckedBehavior : CommandBehaviorBase<CheckBox> { public CheckedBehavior( CheckBox element ) : base( element ) { element.Checked +=new RoutedEventHandler(element_Checked); } void element_Checked( object sender, RoutedEventArgs e ) { base.ExecuteCommand(); } } Command Class public static class Checked { public static ICommand GetCommand( DependencyObject obj ) { return (ICommand) obj.GetValue( CommandProperty ); } public static void SetCommand( DependencyObject obj, ICommand value ) { obj.SetValue( CommandProperty, value ); } public static readonly DependencyProperty CommandProperty = DependencyProperty.RegisterAttached( "Command", typeof( CheckBox ), typeof( Checked ), new PropertyMetadata( OnSetCommandCallback ) ); public static readonly DependencyProperty CheckedCommandBehaviorProperty = DependencyProperty.RegisterAttached( "CheckedCommandBehavior", typeof( CheckedBehavior ), typeof( Checked ), null ); private static void OnSetCommandCallback( DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e ) { CheckBox element = dependencyObject as CheckBox; if( element != null ) { CheckedBehavior behavior = GetOrCreateBehavior( element ); behavior.Command = e.NewValue as ICommand; } } private static CheckedBehavior GetOrCreateBehavior( CheckBox element ) { CheckedBehavior behavior = element.GetValue( CheckedCommandBehaviorProperty ) as CheckedBehavior; if( behavior == null ) { behavior = new CheckedBehavior( element ); element.SetValue( CheckedCommandBehaviorProperty, behavior ); } return behavior; } public static CheckedBehavior GetCheckCommandBehavior( DependencyObject obj ) { return (CheckedBehavior) obj.GetValue( CheckedCommandBehaviorProperty ); } public static void SetCheckCommandBehavior( DependencyObject obj, CheckedBehavior value ) { obj.SetValue( CheckedCommandBehaviorProperty, value ); } } I used this article to get me started, but I'll readily admit this is over my head.

    Read the article

  • Need additional help with binding multiple CommandParameters using MultiBinding

    - by Dave
    I need to have a command handler for a ToggleButton that can take multiple parameters, namely the IsChecked property of said ToggleButton, along with a constant value, which could be a string, byte, int... doesn't matter. I found this great question on SO and followed the answer's link and read up on MultiBinding and IMultiValueConverter. It went really smoothly until I had to write the MultiBinding, when I realized that I also need to pass a constant value and couldn't do something like <Binding Value="1" /> I then came across another similar question that Kent Boogaart answered, and then I started to think about ways that I could get around this. One possible way is to not use MVVM and simply add the Tag property to my ToggleButton, in which case my MultiBinding would look like this: <MultiBinding Converter="{StaticResource MyConverter}"> <MultiBinding.Bindings> <Binding Path="IsChecked" /> <Binding Path="Tag" /> </MultiBinding.Bindings> </MultiBinding> Kent had made a comment along the lines of, "if you're using MVVM you should be able to get around this issue". However, I'm not sure that's an option for me, even though I have adopted MVVM as my WPF pattern of necessity choice. The reason why I say this is that I have wayyyy more than one ToggleButton in the UserControl, and each of the ToggleButtons' Commands need to call the same function. But since they are ToggleButtons, I can't use the property bound to IsChecked in the ViewModel, because I don't know which one was last clicked. I suppose I could add another private property to keep track of this, but it seems a little silly. As far as the constant goes, I could probably get rid of this if I did the tracking idea, but not sure of any other way to get around it. Does anyone have good suggestions for me here? :) EDIT -- ok, so I need to update my bindings, which still don't work quite right: <ToggleButton Tag="1" Command="{Binding MyCommand}" Style="{StaticResource PassFailToggleButtonStyle}" HorizontalContentAlignment="Center" Background="Transparent" BorderBrush="Transparent" BorderThickness="0"> <ToggleButton.CommandParameter> <MultiBinding Converter="{StaticResource MyConverter}"> <MultiBinding.Bindings> <Binding Path="IsChecked" RelativeSource="{RelativeSource Mode=Self}" /> <Binding Path="Tag" RelativeSource="{RelativeSource Mode=Self}" /> </MultiBinding.Bindings> </MultiBinding> </ToggleButton.CommandParameter> </ToggleButton> IsChecked was working, but not Tag. I just realized that Tag is a string... duh. It's working now! The key was to use a RelativeSource of Self.

    Read the article

  • WPF DataGrid and Avalon TimePicker binding problem

    - by Jorge Vargas
    I'm using a the WPF DataGrid from the wpf toolkit and a TimePicker from AvalonControlsLibrary to insert a collection of TimeSpans. My problem is that bindings are not working inside the DataGrid, and I have no clue of why this isn't working. Here is my setup: I have the following XAML: <Window x:Class="Views.TestMainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:wpf="http://schemas.microsoft.com/wpf/2008/toolkit" xmlns:a="http://schemas.AvalonControls/AvalonControlsLibrary/Controls" SizeToContent="WidthAndHeight" MinHeight="250" MinWidth="300"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="*" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <GroupBox Grid.Row="0"> <GroupBox.Header> Testing it: </GroupBox.Header> <wpf:DataGrid ItemsSource="{Binding Path=TestSpans}" AutoGenerateColumns="False"> <wpf:DataGrid.Columns> <wpf:DataGridTemplateColumn Header="Start"> <wpf:DataGridTemplateColumn.CellEditingTemplate> <DataTemplate> <a:TimePicker SelectedTime="{Binding Path=., Mode=TwoWay}" /> </DataTemplate> </wpf:DataGridTemplateColumn.CellEditingTemplate> <wpf:DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding}" /> </DataTemplate> </wpf:DataGridTemplateColumn.CellTemplate> </wpf:DataGridTemplateColumn> </wpf:DataGrid.Columns> </wpf:DataGrid> </GroupBox> <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Grid.Row="1"> <a:TimePicker SelectedTime="{Binding Path=SelectedTime, Mode=TwoWay}" /> </StackPanel> </Grid> And this is my ViewModel: Imports System.Collections.ObjectModel Namespace ViewModels Public Class TestMainWindowViewModel Private _selectedTime As TimeSpan = DateTime.Now.TimeOfDay Public Property SelectedTime() As TimeSpan Get Return _selectedTime End Get Set(ByVal value As TimeSpan) _selectedTime = value End Set End Property Private _testSpans As ObservableCollection(Of TimeSpan) = New ObservableCollection(Of TimeSpan) Public Property TestSpans() As ObservableCollection(Of TimeSpan) Get Return _testSpans End Get Set(ByVal value As ObservableCollection(Of TimeSpan)) _testSpans = value End Set End Property Public Sub New() _testSpans.Add(DateTime.Now.TimeOfDay) _testSpans.Add(DateTime.Now.TimeOfDay) _testSpans.Add(DateTime.Now.TimeOfDay) End Sub End Class End Namespace I'm starting this window in application.xaml.vb like this: Class Application ' Application-level events, such as Startup, Exit, and DispatcherUnhandledException ' can be handled in this file. Protected Overrides Sub OnStartup(ByVal e As System.Windows.StartupEventArgs) MyBase.OnStartup(e) Dim window As Views.TestMainWindow = New Views.TestMainWindow window.DataContext = New TestMainWindowViewModel() window.Show() End Sub End Class

    Read the article

  • Defining a ContextMenu in a DataGridRow style

    - by Brent
    I'm trying to clean up some of my xaml in my views by moving a lot of the DataGrid styles into a ResourceDictionary. One of the things I'd like to move is the ContextMenu that is bound to some commands in the ViewModel. However, when I move the context menu to the ResourceDictionary, the commands are are never firing anymore, and I can't figure out why. I've defined the ContextMenu in the DataGridRow style so that when the user right clicks on the columnheader, no ContextMenu is shown... it will only be shown they right click on a row. Am I doing something wrong here? FYI I'm using VS 2010 RTM if that makes a difference. <Style x:Key="DataGridRowStyle" TargetType="{x:Type DataGridRow}"> <Setter Property="Height" Value="20"/> <Setter Property="ContextMenu"> <Setter.Value> <ContextMenu> <MenuItem Header="New" Command="{Binding RelativeSource={RelativeSource AncestorType=DataGrid}, Path=DataContext.NewCommand}"> <MenuItem.Icon> <Image Source="/Images/DocumentWhite(32N).png" Width="16" Height="16"/> </MenuItem.Icon> </MenuItem> <MenuItem Header="Open" Command="{Binding RelativeSource={RelativeSource AncestorType=DataGrid}, Path=DataContext.OpenCommand}"> <MenuItem.Icon> <Image Source="/Images/FolderOpenYellow(32N).png" Width="16" Height="16"/> </MenuItem.Icon> </MenuItem> <MenuItem Header="Delete" Command="{Binding RelativeSource={RelativeSource AncestorType=DataGrid}, Path=DataContext.DeleteCommand}"> <MenuItem.Icon> <Image Source="/Images/Delete(32N).png" Width="16" Height="16"/> </MenuItem.Icon> </MenuItem> </ContextMenu> </Setter.Value> </Setter> <Style.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="Background" Value="{StaticResource hoverGradient}"/> </Trigger> <Trigger Property="IsSelected" Value="True"> <Setter Property="Background" Value="{StaticResource BtnOverFill}"/> </Trigger> </Style.Triggers> </Style>

    Read the article

  • Why is Html.DropDownList() producing <select name="original_name.name"> instead of just <select name

    - by DanM
    I have an editor template whose job is to take a SelectList as its model and build a select element in html using the Html.DropDownList() helper extension. I'm trying to assign the name attribute for the select based on a ModelMetadata property. (Reason: on post-back, I need to bind to an object that has a different property name for this item than the ViewModel used to populate the form.) The problem I'm running into is that DropDownList() is appending the name I'm providing instead of replacing it, so I end up with names like categories.category instead of category. Here is some code for you to look at... SelectList.ascx <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.Web.Mvc.SelectList>" %> <%= Html.DropDownList( (string)ViewData.ModelMetadata.AdditionalValues["PropertyName"], Model) %> Resulting HTML <select id="SkillLevels_SkillLevel" name="SkillLevels.SkillLevel"> <option value="1">High</option> <option value="2">Med</option> <option selected="selected" value="3">Low</option> </select> Expected HTML <select id="SkillLevels_SkillLevel" name="SkillLevel"> <option value="1">High</option> <option value="2">Med</option> <option selected="selected" value="3">Low</option> </select> Also tried <%= Html.Encode((string)ViewData.ModelMetadata.AdditionalValues["PropertyName"])%> ...which resulted in "SkillLevel" (not "SkillLevels.SkillLevel"), proving that the data stored in metadata is correct. and <%= Html.DropDownList( (string)ViewData.ModelMetadata.AdditionalValues["PropertyName"], Model, new { name = (string)ViewData.ModelMetadata.AdditionalValues["PropertyName"] }) %> ...which still resulted in <select name=SkillLevels.Skilllevel>. Questions What's going on here? Why does it append the name instead of just using it? Can you suggest a good workaround? Update: I ended up writing a helper extension that literally does a find/replace on the html text: public static MvcHtmlString BindableDropDownListForModel(this HtmlHelper helper) { var propertyName = (string)helper.ViewData.ModelMetadata.AdditionalValues["PropertyName"]; var compositeName = helper.ViewData.ModelMetadata.PropertyName + "." + propertyName; var rawHtml = helper.DropDownList(propertyName, (SelectList)helper.ViewData.Model); var bindableHtml = rawHtml.ToString().Replace(compositeName, propertyName); return MvcHtmlString.Create(bindableHtml); }

    Read the article

  • Best practices concerning view model and model updates with a subset of the fields

    - by Martin
    By picking MVC for developing our new site, I find myself in the midst of "best practices" being developed around me in apparent real time. Two weeks ago, NerdDinner was my guide but with the development of MVC 2, even it seems outdated. It's an thrilling experience and I feel privileged to be in close contact with intelligent programmers daily. Right now I've stumbled upon an issue I can't seem to get a straight answer on - from all the blogs anyway - and I'd like to get some insight from the community. It's about Editing (read: Edit action). The bulk of material out there, tutorials and blogs, deal with creating and view the model. So while this question may not spell out a question, I hope to get some discussion going, contributing to my decision about the path of development I'm to take. My model represents a user with several fields like name, address and email. All the names, in fact, on field each for first name, last name and middle name. The Details view displays all these fields but you can change only one set of fields at a time, for instance, your names. The user expands a form while the other fields are still visible above and below. So the form that is posted back contains a subset of the fields representing the model. While this is appealing to us and our layout concerns, for various reasons, it is to be shunned by serious MVC-developers. I've been reading about some patterns and best practices and it seems that this is not in key with the paradigm of viewmodel == view. Or have I got it wrong? Anyway, NerdDinner dictates using FormCollection och UpdateModel. All the null fields are happily ignored. Since then, the MVC-community has abandoned this approach to such a degree that a bug in MVC 2 was not discovered. UpdateModel does not work without a complete model in your formcollection. The view model pattern receiving most praise seems to be Dedicated view model that contains a custom view model entity and is the only one that my design issue could be made compatible with. It entails a tedious amount of mapping, albeit lightened by the use of AutoMapper and the ideas of Jimmy Bogard, that may or may not be worthwhile. He also proposes a 1:1 relationship between view and view model. In keeping with these design paradigms, I am to create a view and associated view for each of my expanding sets of fields. The view models would each be nearly identical, differing only in the fields which are read-only, the views also containing much repeated markup. This seems absurd to me. In future I may want to be able to display two, more or all sets of fields open simultaneously. I will most attentively read the discussion I hope to spark. Many thanks in advance.

    Read the article

  • Modelling a checkable treeview in the MVVM model

    - by Stephen Stranded
    Hi, I am trying to create a checkable treeview control to list hierarchical data but it does not seem to work. I used the MVVM model example used by in codeplex simplified Treeview using ViewModel but it shows nothing. Here is my code. Please help. I am a newbie to WPF and the MVVM model but i very much want to use it in an urgent application. </UserControl.Resources> <Grid> <StackPanel Height="166"> <TextBlock Text="Please Display this" /> <TreeView ItemsSource="{Binding Classifications}" Height="141"> <TreeView.ItemContainerStyle> <!-- This Style binds a TreeViewItem to a TreeViewItemViewModel. --> <Style TargetType="{x:Type TreeViewItem}"> <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" /> <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" /> <Setter Property="FontWeight" Value="Normal" /> <Style.Triggers> <Trigger Property="IsSelected" Value="True"> <Setter Property="FontWeight" Value="Bold" /> </Trigger> </Style.Triggers> </Style> </TreeView.ItemContainerStyle> <TreeView.Resources> <HierarchicalDataTemplate DataType="{x:Type local:PropertyTypeViewModel}" ItemsSource="{Binding Children}"> <StackPanel Orientation="Horizontal"> <CheckBox Focusable="false" IsChecked="{Binding isSelected}"></CheckBox> <TextBlock Text="{Binding Classification}" /> </StackPanel> </HierarchicalDataTemplate> <HierarchicalDataTemplate DataType="{x:Type local:PropertyViewModel}" ItemsSource="{Binding Children}" > <StackPanel Orientation="Horizontal"> <CheckBox Focusable="false" IsChecked="{Binding isSelected}"></CheckBox> <TextBlock Text="{Binding PropertyName}" /> </StackPanel> </HierarchicalDataTemplate> <DataTemplate DataType="{x:Type local:LeaseViewModel}"> <StackPanel Orientation="Horizontal"> <CheckBox Focusable="false" IsChecked="{Binding isSelected}"></CheckBox> <TextBlock Text="{Binding TenantName}" /> </StackPanel> </DataTemplate> </TreeView.Resources> </TreeView> </StackPanel> </Grid>

    Read the article

  • knockout.js bind to static data

    - by MatteS
    whats the suggested way to bind to existing static data? I have to include this in the viewmodel because its used in computed values. http://jsfiddle.net/z2ykC/4/ <div id="sum" data-bind="text: sum"> </div> <div class="line"> dynamic: <span data-bind="text: dynamicValue"></span> static: <span data-bind="text: staticValue">312</span> <button data-bind="click: getDataFromServer">get data</button> </div> <div class="line"> dynamic: <span data-bind="text: dynamicValue"></span> static: <span data-bind="text: staticValue">123</span> <button data-bind="click: getDataFromServer">get data</button> </div> ? function SumViewModel(lines){ this.sum = ko.computed(function(){ var value = 0; $.each(lines, function(index, element){ var staticValue = element.staticValue(); if (staticValue) value += staticValue; var dynamicValue = element.dynamicValue(); if (dynamicValue) value += dynamicValue; value += dynamicValue; }); return value; }); } function LineViewModel() { this.randomNumber = function(max) { return Math.floor((Math.random() * max) + 1); }; this.dynamicValue = ko.observable(0); this.staticValue = ko.observable(); this.getDataFromServer = function() { this.dynamicValue(this.randomNumber(300)); }; }; var lines = []; $('.line').each(function(index, element) { var line = new LineViewModel() //line.staticValue(parseInt($('[data-bind*="staticValue"]', element).text())); lines.push(line); ko.applyBindings(line, element); }); var sum = new SumViewModel(lines); ko.applyBindings(sum, $('#sum')[0]);

    Read the article

  • Linq to SQL Repository ~theory~ - Generic but now uses Linq to Objects?

    - by Matt Tolliday
    The project I am currently working on used Linq to SQL as an ORM data access technology. Its an MVC3 Web app. The problem I faced was primarily due to the inability to mock (for testing) the DataContext which gets autogenerated by the DBML designer. So to solve this issue (after much reading) I refactored the repository system which was in place - single repository with seperate and duplicated access methods for each table which ended up with something like 300 methods only 10 of which were unique - into a single repository with generic methods taking the table and returning more generic types to the upper reaches of the application. My question revolves more around the design I've used to get thus far and the differences I'm noticing in the structure of the app. 1) Having refactored the code from the dark ages which used classic Linq to SQL queries: public Billing GetBilling(int id) { var result = ( from bil in _bicDc.Billings where bil.BillingId == id select bil).SingleOrDefault(); return (result); } it now looks like: public T GetRecordWhere<T>(Expression<Func<T, bool>> predicate) where T : class { T result; try { result = _dataContext.GetTable<T>().Where(predicate).SingleOrDefault(); } catch (Exception ex) { throw ex; } return result; } and is used by the controller with a query along the lines of: _repository.GetRecordWhere<Billing>(x => x.BillingId == 1); which is fine, and precisely what I wanted to achieve. ...however.... I'm also having to do the following to get precisely the result set i require in the controller class (the highest point of the app in essence)... viewModel.RecentRequests = _model.GetAllRecordsWhere<Billing>(x => x.BillingId == 1) .Where(x => x.BillingId == Convert.ToInt32(BillingType.Submitted)) .OrderByDescending(x => x.DateCreated). Take(5).ToList(); This - as far as my understanding is correct - is now using Linq to Objects rather than the Linq to SQL queries I was previously? Is this okay practise? It feels wrong to me but I dont know why. Probably because the logic of the queries is in the very highest tier of the app, rather than the lowest, but... I defer to you good people for advice. One of the issues I considered was bringing the entire table into memory but I understand that using the Iqeryable return type the where clause is taken to the database and evaluated there. Thus returning only the resultset i require... i may be wrong. And if you've made it this far, well done. Thank you, and if you have any advice it is very much appreciated!!

    Read the article

  • How can I model the data in a multi-language data editor in WPF with MVVM?

    - by Patrick Szalapski
    Are there any good practices to follow when designing a model/ViewModel to represent data in an app that will view/edit that data in multiple languages? Our top-level class--let's call it Course--contains several collection properties, say Books and TopicsCovered, which each might have a collection property among its data. For example, the data needs to represent course1.Books.First().Title in different languages, and course1.TopicsCovered.First().Name in different languages. We want a app that can edit any of the data for one given course in any of the available languages--as well as edit non-language-specific data, perhaps the Author of a Book (i.e. course1.Books.First().Author). We are having trouble figuring out how best to set up the model to enable binding in the XAML view. For example, do we replace (in the single-language model) each String with a collection of LanguageSpecificString instances? So to get the author in the current language: course1.Books.First().Author.Where(Function(a) a.Language = CurrentLanguage).SingleOrDefault If we do that, we cannot easily bind to any value in one given language, only to the collection of language values such as in an ItemsControl. <TextBox Text={Binding Author.???} /> <!-- no way to bind to the current language author --> Do we replace the top-level Course class with a collection of language-specific Courses? So to get the author in the current language: course1.GetLanguage(CurrentLanguage).Books.First.Author If we do that, we can only easily work with one language at a time; we might want a view to show one language and let the user edit the other. <TextBox Text={Binding Author} /> <!-- good --> <TextBlock Text={Binding ??? } /> <!-- no way to bind to the other language author --> Also, that has the disadvantage of not representing language-neutral data as such; every property (such as Author) would seem to be in multiple languages. Even non-string properties would be in multiple languages. Is there an option in between those two? Is there another way that we aren't thinking of? I realize this is somewhat vague, but it would seem to be a somewhat common problem to design for. Note: This is not a question about providing a multilingual UI, but rather about actually editing multi-language data in a flexible way.

    Read the article

  • Trouble binding command in grid menu item.

    - by Pete
    I have a grid that's inside a usercontrol derived class called MediatedUserControl. I'm adding a context menu to let the user delete an item, but I've been unable to figure out how to bind the command to my command property. I'm using MVVM and my viewmodel implements a public ICommand property called DeleteSelectedItemCommand. However, when the view is displayed, I get the following message in the output window: System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='BRO.View.MediatedUserControl', AncestorLevel='1''. BindingExpression:Path=DataContext.DeleteSelectedItemCommand; DataItem=null; target element is 'BarButtonItem' (HashCode=6860584); target property is 'Command' (type 'ICommand') I feel like I generally have a good handle on bindings like this and can't figure out what it is I'm missing here. Thanks for any help you can provide. <dxg:GridControl HorizontalAlignment="Left" Margin="12,88,0,0" x:Name="gridControl1" VerticalAlignment="Top" Height="500" Width="517" DataSource="{Binding ItemList}" BorderBrush="{StaticResource {x:Static SystemColors.ActiveBorderBrushKey}}" ShowBorder="True" Background="{StaticResource {x:Static SystemColors.ControlLightBrushKey}}" UseLayoutRounding="False" DataContext="{Binding}"> <dxg:GridControl.Columns> <dxg:GridColumn FieldName="Code" Header="Code" Width="107" /> <dxg:GridColumn FieldName="Name" Header="Item" Width="173" /> <dxg:GridColumn FieldName="PricePerItem" Header="Unit Price" Width="70"> <dxg:GridColumn.EditSettings> <dxe:TextEditSettings DisplayFormat="N2" /> </dxg:GridColumn.EditSettings> </dxg:GridColumn> <dxg:GridColumn FieldName="Quantity" Header="Qty" Width="50" AllowEditing="True" /> <dxg:GridColumn FieldName="TotalPrice" Header="Total Price" Width="90"> <dxg:GridColumn.EditSettings> <dxe:TextEditSettings DisplayFormat="N2" /> </dxg:GridColumn.EditSettings> </dxg:GridColumn> </dxg:GridControl.Columns> <dxg:GridControl.View> <dxg:TableView ShowIndicator="False" ShowGroupPanel="False" MultiSelectMode="Row" AllowColumnFiltering="False" AllowBestFit="False" AllowFilterEditor="False" AllowEditing="False" AllowGrouping="False" AllowSorting="False" AllowResizing="False" AllowMoving="False" AllowMoveColumnToDropArea="False" AllowDateTimeGroupIntervalMenu="False" > <dxg:TableView.RowCellMenuCustomizations> <dxb:BarButtonItem Name="deleteRowItem" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=view:MediatedUserControl, AncestorLevel=1}, Path=DataContext.DeleteSelectedItemCommand}"> </dxb:BarButtonItem> </dxg:TableView.RowCellMenuCustomizations> </dxg:TableView> </dxg:GridControl.View>

    Read the article

  • SelectList in Asp-mvc and data from the database

    - by George
    Hello guys. I'm having some troubles with SelectList in ASP.MVC. Here is the issue: I have a Create View and begind a ViewModel model. The page load just fine (GET verb). But when posting, something happens, and my model is considered invalid, and it cannot insert. Here's what i've tried so far. public class DefinitionFormViewModel { private Repository<Category> categoryRepository = new Repository<Category>(); public Definition ViewDefinition { get; private set; } public SelectList Categories { get; private set; } public DefinitionFormViewModel(Definition def) { ViewDefinition = def; // here i wanted to place it directly, like shown in NerdDinner Tutorial // new SelectList(categoryRepository.All(),ViewDefinition.Category); Categories = new SelectList(categoryRepository.All(), "CategoryId", "CategoryName", ViewDefinition.CategoryId); } } // pageview which inherits DefinitionFormViewModel <div class=editor-field"> <%= Html.DropDownList("Category",Model.Categories) %> <%= Html.ValidationMessageFor(model => Model.ViewDefinition.Category) %> </div> // controller methods [Authorize] public ActionResult Create() { Definition definition = new Definition(); return View(new DefinitionFormViewModel(definition)); } [AcceptVerbs(HttpVerbs.Post), Authorize] public ActionResult Create(int id,Definition definition) { Term term = termRepository.SingleOrDefault(t => t.TermId == id); if (term == null) { return View("NotFound", new NotFoundModel("Termo não encontrado", "Termo não encontrado", "Nos desculpe, mas não conseguimos encontrar o termo solicitado.", "Indíce de Termos", "Index", "Term")); } else { if (ModelState.IsValid) { try { definition.TermId = term.TermId; definition.ResponsibleUser = User.Identity.Name; UpdateModel(definition); term.Definitions.Add(definition); termRepository.SaveAll(); return RedirectToAction("Details", "Term", new { id = term.TermId }); } catch (System.Data.SqlClient.SqlException sqlEx) { ModelState.AddModelError("DatabaseError", "Houve um erro na inserção desta nova definição"); } catch { foreach (RuleViolation rv in definition.GetRuleViolations()) { ModelState.AddModelError(rv.PropertyName, rv.ErrorMessage); } } } } return View(new DefinitionFormViewModel(definition)); } I'm sorry about the long post, but I cant figure this out. I got no graphic errors or exceptions. My execution terminates in if (ModelState.IsValid). Thanks for your time George

    Read the article

  • How can I specify resources in an MVVM view model?

    - by gix
    Suppose I want to show list of objects where each object should have a name and a suitable image (for example MenuItems with Icons, or buttons with text and image). All examples and programs exposed the image in the viewmodel as a path to a PNG file and then bound the Source of an Image to that. But what if I want to use vector images (for example as a DrawingImage in a local ResourceDictionary)? Exposing the DrawingImage from the view model seems bad because I would have to store a reference to the application/window/user control/... (and it is advised to not expose such XAML objects from view models). So a better approach would be to use a string identifier in the view model and then somehow select the appropriate resource. If that identifier is the resource key this snippet looks tempting but does not work: <Image Source="{StaticResource {Binding Icon}}"/> I found two workarounds for that though they did not work for me. The first one was using a normal binding to the icon with a converter that looked up the resource in Application.Current. This does not work if the resource is stored somewhere else I think (and the situation where I initially bumped into this problem had no Application running yet since it was a Window choosing the Application to launch!). The second workaround was using a markup extension derived from StaticResourceExtension that fetched its ResourceKey from the passed binding: <Image Source="{local:BindableStaticResource {Binding Icon}"/> This one looks really neat because it could use local resources, also be used for other things. But when using it I always got an exception ("Resource named {FooIcon} could not be found.", showing the correct XAML file and position of the extension). Even an empty resource extension derived from StaticResourceExtension that just passed the resource key to the base constructor did not work and I cannot explain why. Just using StaticResourceExtension worked just fine. Any ideas how I could fix the second approach, or even better solutions? Edit I noticed that it does work when used directly like this: <Window> <Window.Resources> <DrawingImage x:Key="SomeIcon"/> </Window.Resources> <Image Source="{BindableStaticResource {Binding Icon}}"/> </Window> but fails for example in a DataTemplate. Though a normal StaticResourceExtension works on both occasions so I am puzzled what is going wrong.

    Read the article

  • Unable to add item to dataset in Linq to SQL

    - by Mike B
    I am having an issue adding an item to my dataset in Linq to SQL. I am using the exact same method in other tables with no problem. I suspect I know the problem but cannot find an answer (I also suspect all i really need is the right search term for Google). Please keep in mind this is a learning project (Although it is in use in a business) I have posted my code and datacontext below. What I am doing is: Create a view model (Relevant bits are shown) and a simple wpf window that allows editing of 3 properties that are bound to the category object. Category is from the datacontext. Edit works fine but add does not. If I check GetChangeSet() just before the db.submitChanges() call there are no adds, edits or deletes. I suspect an issue with the fact that a Category added without a Subcategory would be an orphan but I cannot seem to find the solution. Command code to open window: CategoryViewModel vm = new CategoryViewModel(); AddEditCategoryWindow window = new AddEditCategoryWindow(vm); window.ShowDialog(); ViewModel relevant stuff: public class CategoryViewModel : ViewModelBase { public Category category { get; set; } // Constructor used to Edit a Category public CategoryViewModel(Int16 categoryID) { db = new OITaskManagerDataContext(); category = QueryCategory(categoryID); } // Constructor used to Add a Category public CategoryViewModel() { db = new OITaskManagerDataContext(); category = new Category(); } } The code for saving changes: // Don't close window unless all controls are validated if (!vm.IsValid(this)) return; var changes = vm.db.GetChangeSet(); // DEBUG try { vm.db.SubmitChanges(ConflictMode.ContinueOnConflict); } catch (ChangeConflictException) { vm.db.ChangeConflicts.ResolveAll(RefreshMode.KeepChanges); vm.db.SubmitChanges(); } The Xaml (Edited fror brevity): <TextBox Text="{Binding category.CatName, Mode=TwoWay, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" /> <TextBox Text="{Binding category.CatDescription, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" /> <CheckBox IsChecked="{Binding category.CatIsInactive, Mode=TwoWay}" /> IssCategory in the Issues table is the old, text based category. This field is no longer used and will be removed from the database as soon as this is working and pushed live.

    Read the article

  • Can't access font resource in Silverlight class library

    - by Matt
    I have a reasonably large Silveright 3.0 project on the go, and I'm having issues accessing a couple of custom font resources from within one of the assemblies. I've got a working test solution where I have added a custom font as a resource, and can access it fine from XAML using: <TextBlock Text="Test" FontFamily="FontName.ttf#Font Name" /> The test solution consists of the TestProject.Application and the TestProject.Application.Web projects, with all the fun and games obviously in the TestProject.Application project However, when I try this in my main solution, the fonts refuse to show in the correct type face (instead showing in the default font). There's no difference in the way the font has been added to project between the test solution and the main solution, and the XAML is identical. However, there is a solution layout difference. In the main solution, as well as having a MainApp.Application and MainApp.Application.Web project, I also have a MainApp.Application.ViewModel project and a MainApp.Application.Views project, and the problem piece of XAML is the in the MainApp.Application.Views project (not the .Application project like the test solution). I've tried putting the font into either the .Application or .Application.Views project, tried changing the Build Action to Content, Embedded Resource etc, all to no avail. So, is there an issue accessing font resources from a child assembly that I don't know about, or has anyone successfully done this? My long term need will be to have the valid custom fonts being stored as resources in a separate .Application.FontLibrary assembly that will be on-demand downloaded and cached, and the XAML controls in the .Application.Views project will need to reference this FontLibrary assembly to get the valid fonts. I've also tried xcreating this separate font library assembly, and I can't seem to get the fonts from the second assembly. As some additional information, I've also tried the following font referencing approaches: <TextBlock Text="Test" FontFamily="/FontName.ttf#Font Name" /> <TextBlock Text="Test" FontFamily="pack:application,,,/FontName.ttf#Font Name" /> <TextBlock Text="Test" FontFamily="pack:application,,,/MainApp.Application.Views;/FontName.ttf#Font Name" /> <TextBlock Text="Test" FontFamily="pack:application,,,/MainApp.Application.Views;component/FontName.ttf#Font Name" /> And a few similar variants with different assembly references/sub directories/random semi colons. And so far nothing works... anyone struck this (and preferably solved it)?

    Read the article

  • How to perform duplicate key validation using entlib (or DataAnnotations), MVC, and Repository pattern

    - by olivehour
    I have a set of ASP.NET 4 projects that culminate in an MVC (3 RC2) app. The solution uses Unity and EntLib Validation for cross-cutting dependency injection and validation. Both are working great for injecting repository and service layer implementations. However, I can't figure out how to do duplicate key validation. For example, when a user registers, we want to make sure they don't pick a UserID that someone else is already using. For this type of validation, the validating object must have a repository reference... or some other way to get an IQueryable / IEnumerable reference to check against other rows already in the DB. What I have is a UserMetadata class that has all of the property setters and getters for a user, along with all of the appropriate DataAnnotations and EntLib Validation attributes. There is also a UserEntity class implemented using EF4 POCO Entity Generator templates. The UserEntity depends on UserMetadata, because it has a MetadataTypeAttribute. I also have a UserViewModel class that has the same exact MetadataType attribute. This way, I can apply the same validation rules, via attributes, to both the entity and viewmodel. There are no concrete references to the Repository classes whatsoever. All repositories are injected using Unity. There is also a service layer that gets dependency injection. In the MVC project, service layer implementation classes are injected into the Controller classes (the controller classes only contain service layer interface references). Unity then injects the Repository implementations into the service layer classes (service classes also only contain interface references). I've experimented with the DataAnnotations CustomValidationAttribute in the metadata class. The problem with this is the validation method must be static, and the method cannot instantiate a repository implementation directly. My repository interface is IRepository, and I have only one single repository implementation class defined as EntityRepository for all domain objects. To instantiate a repository explicitly I would need to say new EntityRepository(), which would result in a circular dependency graph: UserMetadata [depends on] DuplicateUserIDValidator [depends on] UserEntity [depends on] UserMetadata. I've also tried creating a custom EntLib Validator along with a custom validation attribute. Here I don't have the same problem with a static method. I think I could get this to work if I could just figure out how to make Unity inject my EntityRepository into the validator class... which I can't. Right now, all of the validation code is in my Metadata class library, since that's where the custom validation attribute would go. Any ideas on how to perform validations that need to check against the current repository state? Can Unity be used to inject a dependency into a lower-layer class library?

    Read the article

  • Why is my namespace not recognized in Visual Studio / xaml

    - by msfanboy
    Hello, these are my 2 classes a Attachable Property SelectedItems: code is from here: http://stackoverflow.com/questions/1297643/sync-selecteditems-in-a-muliselect-listbox-with-a-collection-in-viewmodel The namespace TBM.Helper is for sure proper as it works for other classes too. The namespace reference is also in the xaml file: xmlns:Helper="clr_namespace:TBM.Helper" But <ListBox Helper:SelectedItems.Items="{Binding SelectedItems}" ... does not work because = The property 'SelectedItems.Items' does not exist in XML namespace 'clr_namespace:TBM.Helper'. The attachable property 'Items' was not found in type 'SelectedItems What do I have to change ? using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Controls; using System.Collections; using System.Windows; namespace TBM.Helper { public static class SelectedItems : DependencyObject { private static readonly DependencyProperty SelectedItemsBehaviorProperty = DependencyProperty.RegisterAttached( "SelectedItemsBehavior", typeof(SelectedItemsBehavior), typeof(ListBox), null); public static readonly DependencyProperty ItemsProperty = DependencyProperty.RegisterAttached( "Items", typeof(IList), typeof(SelectedItems), new PropertyMetadata(null, ItemsPropertyChanged)); public static void SetItems(ListBox listBox, IList list) { listBox.SetValue(ItemsProperty, list); } public static IList GetItems(ListBox listBox) { return listBox.GetValue(ItemsProperty) as IList; } private static void ItemsPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var target = d as ListBox; if (target != null) { GetOrCreateBehavior(target, e.NewValue as IList); } } private static SelectedItemsBehavior GetOrCreateBehavior(ListBox target, IList list) { var behavior = target.GetValue(SelectedItemsBehaviorProperty) as SelectedItemsBehavior; if (behavior == null) { behavior = new SelectedItemsBehavior(target, list); target.SetValue(SelectedItemsBehaviorProperty, behavior); } return behavior; } } } using System.Windows; using System.Windows.Controls; using System.Collections; namespace TBM.Helper { public class SelectedItemsBehavior { private readonly ListBox _listBox; private readonly IList _boundList; public SelectedItemsBehavior(ListBox listBox, IList boundList) { _boundList = boundList; _listBox = listBox; SetSelectedItems(); _listBox.SelectionChanged += OnSelectionChanged; _listBox.DataContextChanged += OnDataContextChanged; } private void SetSelectedItems() { _listBox.SelectedItems.Clear(); foreach (object item in _boundList) { // References in _boundList might not be the same as in _listBox.Items int i = _listBox.Items.IndexOf(item); if (i >= 0) _listBox.SelectedItems.Add(_listBox.Items[i]); } } private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { SetSelectedItems(); } private void OnSelectionChanged(object sender, SelectionChangedEventArgs e) { _boundList.Clear(); foreach (var item in _listBox.SelectedItems) _boundList.Add(item); } } }

    Read the article

  • GridView's ItemContainerStyle and selection states

    - by Roberto Casadei
    I'm trying to change the appearance of gridview items when they are selected. (Before, I used a trick with an IsSelected property in the ViewModel object bound to the containing grid and a bool-to-color converter, but I recognize that it is bad) To do so, I do: <GridView ItemContainerStyle="{StaticResource GridViewItemContainerStyle}" ...> ... and <Style x:Key="GridViewItemContainerStyle" TargetType="GridViewItem"> <Setter Property="Background" Value="Red" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="GridViewItem"> <Grid> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CommonStates"> <VisualState x:Name="Normal"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(Grid.Background)" Storyboard.TargetName="itemGrid"> <DiscreteObjectKeyFrame KeyTime="0" Value="Black"/> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> </VisualStateGroup> <VisualStateGroup x:Name="SelectionStates"> <VisualState x:Name="UnselectedSwiping"/> <VisualState x:Name="UnselectedPointerOver"/> <VisualState x:Name="Selecting"/> <VisualState x:Name="Selected"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(Grid.Background)" Storyboard.TargetName="itemGrid"> <DiscreteObjectKeyFrame KeyTime="0" Value="White"/> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="SelectedSwiping"/> <VisualState x:Name="Unselecting"/> <VisualState x:Name="Unselected"/> <VisualState x:Name="SelectedUnfocused"/> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <Grid ... x:Name="itemGrid"> <!-- HERE MY DATA TEMPLATE --> </Grid> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> When I run the app, the items are Black (as in the "normal" state). But selecting them does not turn them into White. Where am I wrong? Moreover, it there a way to set "ItemContainerStyle" without having it to "overwrite" the "ItemTemplate" ???

    Read the article

< Previous Page | 28 29 30 31 32 33 34 35 36  | Next Page >