Showing posts with label WPF. Show all posts
Showing posts with label WPF. Show all posts

Thursday, August 22, 2013

WPF - The dependency property is already registered


This is the error you will face when you are copy pasting the code to write dependency property. JJoking…That is not the reason of this error. But I have received it when I copy pasted dependency property code from one of the site.
You will land up in this error when you have dependency property written in following way –
public readonly DependencyProperty SelectedItems2 =
            DependencyProperty.Register("SelectedItems2", typeof(string), typeof(ListBox), new PropertyMetadata(null));

What is missing here? - STATIC keyword.
The problem lies in a way you register your dependency property. You should not register in the default constructor of the class, but in static constructor or initialize it at the time of declaration and preceding with Static keyword. Best way to write dependency property without error is code snippet. Type ‘propdp’ then press tab twice. And then customize the property as per your requirement. This is how you can avoid this error; avoid learning of dependency property syntax and save time.
public static readonly DependencyProperty SelectedItems2 =
            DependencyProperty.Register("SelectedItems2", typeof(string), typeof(ListBox), new PropertyMetadata(null));

Hope this helps.
Cheers…
Happy Properting!!!

Tuesday, August 20, 2013

Value produced by BindingExpression is not valid for target property – WPF-MVVM-Prism and Telerik control



Ahhh, Telerik - what a pain this is…Telerik controls have made my life bit hard…
I am using MaskedTextInput control and trying to Clear the text in it on the click on Clear button which is inbuilt in this control. It clears the text however does not clear the value in property bind to it in XAML. To understand what I mean here refer to following tag –
<ams:AmsMaskedTextInput Value="{Binding TemperatureValue,Mode=TwoWay, NotifyOnSourceUpdated=True,ValidatesOnDataErrors=True}" Mask="###.#" Placeholder=" " Width="150" HorizontalAlignment="Left" /> 

Here if I click on the default clear button available in masked text input, it clears the entered text however value entered by user persisted in TemperatureValue  property. So my aim to make the binding property set to null on click of default clear button available in masked input text control.
I was using the MVVM-Prism framework an hence I defined my command in view model as –
Microsoft.Practices.Prism.Commands.DelegateCommand TemperatureClearCommand { get; private set; } 
 
In initialize view model – TemperatureClearCommand = new Microsoft.Practices.Prism.Commands.DelegateCommand (OnMaskedTextInputClear);
And in callback method –
public void OnMaskedTextInputClear()
        {
                TemperatureValue = null;
                NotifyPropertyChanged(() => TemperatureValue);
        } 

Updated the XAML as follows –

Friday, July 5, 2013

The function import cannot be executed because it is not mapped to a store function



This is very typical error you receive when your underlying database store is changed and there is no update made to EDMX file.
For example, I imported a stored procedure in edmx and saved it. After that I change the stored procedure and do not update edmx. I run the application and at runtime the error is encountered as - “the function import cannot be executed because it is not mapped to a store function”.
This error can be resolved easily by updating the edmx. Following is procedure to resolve the error –
Open the edmx and open Model Browser. Model browser can be opened as shown below.
 
Find the required stored procedure in model browser. The right click and select option – “Delete from Model” as shown below –
 
Now right click on any area on edmx file and select the option “Update Model from Database” option. The popup containing the list of Tables, View and stored procedure will appear. Select the earlier deleted stored procedure and click “Finish” on the pop up.
Now again open the model browser and find the added stored procedure. Right click on it and select the “Edit” option as shown below -

Friday, June 21, 2013

ListBox Data template in WPF MVVM sample



This post talks about using Data Template in WPF – MVVM. As an example I am using ListBox control. The items will be added to listbox based on data template bindings. As basic configuration create a WPF proect. Add View Models folder. I have added another project in the same solution – BusinessLayer. This actually returns list of Tasks that need to be displayed in ListBox. The final solution structure is as follows –
 

Business Layer has a class Task and TaskManager. The TaskManager class is used to create a list of Tasks which will be displayed in ListBox. The Task.cs is as follows –
public class Task
    {
        public string Name { get; set; }
 
        public string Description { get; set; } 

        public int Priority { get; set; }
    }
The TaskManager.cs contains the method to get the list of tasks. As it is very simple; I am skipping it. As part of this sample I have created a ViewModelBase class which contains the implementation of INotifyPropertyChanged  and my specific view model inherits from this base class. The code of my view model class is as follows -  
public class ViewModelBase : INotifyPropertyChanged
    {
       #region INotifyPropertyChanged implementation
        public event PropertyChangedEventHandler PropertyChanged;

        public void NotifyPropertyChanged(string propertyName)

Thursday, June 13, 2013

InkCanvas in WPF – MVVM – StrokeCollection binding


 
After long time, I got some good quality work in this project. Today I used InkCanvas in WPF-MVVM. Then I saved the shapes or drawing drawn within, to database.
Saving anything to database is OK, but the issues is – how do you get the byte array from InkCanvas Strokes? Een the major issue is how do get Strokes from InkCanvas?
Below article explains InkCanvas binding in WPF – MVVM. Alright then, to start with create a WPF project. Have ViewModel folder added in it; to have logic separation from Views. So final Structure of you application will be as follows –

 

Add InkCanvas in your XAML file and Ellipse in it to have drawing within it as written below –
<Window x:Class="StokesCollectionInMVVM.MainWindow"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <InkCanvas Background="Aqua" Strokes="{Binding StrokesEllipse}">
        <Ellipse Height="100" HorizontalAlignment="Left" Margin="116,100,0,0" Name="ellipse1" Stroke="Black" VerticalAlignment="Top" Width="200" />   
        </InkCanvas>
    </Grid>
</Window>

The view model code will be as follows –
Class variables and View model class definition is as follows –
public class MainWindowsViewModel : INotifyPropertyChanged
    {
        #region INotifyPropertyChanged implementation
        public event PropertyChangedEventHandler PropertyChanged; 

        private void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion 

        #region Class variables       

        private StrokeCollection _strokesEllipse = null;

        #endregion

In constructor – [Note – Code to save byte array in database and retrieve it from database is skipped]
public MainWindowsViewModel()
        {
            //to autopopulate saved drawing on UI -
            //read byte array from say - database and store in EllipseDrawing property
            if (EllipseDrawing != null)
            {
                using (var memoryStream = new MemoryStream(EllipseDrawing))
                {
                    _strokesEllipse = new StrokeCollection(memoryStream);
                }
            }
            else
            {
                _strokesEllipse = new StrokeCollection();
            } 

            (_strokesEllipse as INotifyCollectionChanged).CollectionChanged += new NotifyCollectionChangedEventHandler(MainWindowsViewModel_CollectionChanged);
        }
The handler method of this event is as follows – [Note – Code to save byte array in database and retrieve it from database is skipped]

Tuesday, May 21, 2013

Checkbox WPF – Making checkbox readonly in WPF


As the title suggests, following is the way by which you can make a checkbox readonly in WPF.
Let’s have a look at typical checkbox XAML –
<CheckBox Content="CheckBox" Name="checkBox1" />
Now to make this checkbox read only – we need to add two following properties to XAML statement above.

Those two Properties are – IsHitTestVisible and Focusable
Make thse two properties to False. This makes the readonly checkbox in WPF.
So final XAML statement will be as follows for readonly checkbox in WPF –  

<CheckBox Content="CheckBox" Name="checkBox1" IsHitTestVisible="False" Focusable="False"/> 

Hope this helps.

Cheers…

Happy Coding!!

Monday, September 3, 2012

WPF custom control and adding DependencyProperty to custom control


To create custom control in WPF, choose WPF Custom Control Library project in VS2010. Then rename the default added class to your choice. I am trying to create a custom list box with few user added properties in it. Then add a WPF project which will use this custom list box in it. So my solution structure is as follows –

Now I am going to add dependency properties in the class file. These properties will be then available in Properties window once you use the control in any WPF application.

Thursday, August 30, 2012

WPF – MVVM – Combobox binding with enums


WPF and MVVM is going smooth for me at least as of now. Today, I am going to disucss how combobx binding with enum can be done in MVVM pattern. Here I assume that, you have basic idea of MVVM and how it can be used with WPF applications. The MVVM explaination is out of scope for this blog post.
First of all create simple WPF application named as EnumToDDLBinding using VS2010. You can give any name as per your choice. If so then make sure that, you replace the namespace names in codes mentioned below with your namespace name.  Add a new folder named as “ViewModel”. Add a new class in it named as “MainWindowViewModel.cs. The add another class in solution and name it as “MyEnum.cs”.
 The overall structure of solution is as shown below –
 
Add sample enum to MyEnum.cs as shown below –
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; 

Tuesday, July 10, 2012

WPF Binding – Element Binding example - Enable Disable Control based on another control property in WPF

Gone are the days for me to work on Azure. 3 weeks back started with WPF. I have been in web technology for last 5 years and now suddenly shifted to windows applications using WPF.
Now struggling with binding, converters and what not. Anyways, I have started to digest simple WPF concepts one of which I am going to discuss here.
I want to bind a controls property “IsEnabled” to another controls property value. As an example, I am taking the textbox control to enable or disable based on the selction of value in drop down. Ohh sorry, combobox!!! (drop down we generally refer in web application!!)
Lets create a simple WPF application, add two controls viz. combobox and textbox. I created a simple class having 2 properties value and text. This class I will use to bind to combo box. The class is as shown –
public class MyItem
    {
        public int Value { get; set; } 

        public string Text { get; set; }
    } 

    public class MyItems : ObservableCollection<MyItem>
    {
    }