Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Che Delilas
Nov 23, 2009
FREE TIBET WEED

Knyteguy posted:

No luck unfortunately. Thanks though.

I feel like Windows 8.1 Phone development is still in beta stages or something. Not a whole lot of helpful debugging information.

It could be a Visual Studio bug - I hate to suggest this because it sounds so Tier 1 Helpdesk, but have you tried Cleaning your solution, exiting Visual Studio, then restarting it and Rebuilding your solution?

I've had VS gently caress up in similar ways in the past, being unable to find classes that I knew were there and the like, specifically with XAML. Restarting the IDE tended to fix it.

Adbot
ADBOT LOVES YOU

Mr. Crow
May 22, 2008

Snap City mayor for life
Are either one new? WPF has an issue where it won't compile XAML if some resource your referencing hadn't been built yet, I'm not 100% sure the specific scenario it occurs. Try commenting the data part.

raminasi
Jan 25, 2005

a last drink with no ice
I've seen that problem when the assembly containing the viewmodel gets renamed in a post-build event. Basically, Intellisense knows what the class will look like once compiled, but the compiler can't actually find it once it is.

Gul Banana
Nov 28, 2003

ljw1004 posted:

Sorry, that was partly my doing. The reason for not doing them in VB is:

* We foresee something nicer coming along, e.g. https://roslyn.codeplex.com/discussions/560339
In C# the primary constructor syntax will already be taken, so C# would have to express "plain old data" objects with some kind of other syntax e.g. "record class Point(int x, int y);" and there'll be several similar kinds of things. In VB, if we don't do primary constructors now, then we'll leave the syntax free for the something nicer in the future.

case classes/ records/ POVBOs are exactly what I want (and wanted primary constructors as a step towards), so that's a pretty good reason!

A Tartan Tory
Mar 26, 2010

You call that a shotgun?!
I feel like a complete idiot newbie for asking this but...well...I am a complete idiot newbie!

I am trying to use WPF to let the user type in a variable into a text box, then use that variable in a background class to do various calculations with, then spit out the results of these nested calculations in another results page in the form of a data grid from an array variable. I understand that I need to use data binding to do this and have a fair idea of how to create the results page, but I have absolutely no idea whatsoever how to take that value from the text box, move the data over to another class and convert it into a double for future use for nested calculations within that class.

Could anyone show me how I go about taking the user inputted data from a XAML textbox and use it to declare a variable in the background code? And how to convert it from (presumably a string) to a double? Preferably with a small example of like one text box and one declaration in the background code or even just point me to an existing example of it.

There are lots of examples online when I looked for using the inputted value in another XAML object, but none for actually using it in the code that I could see. So sorry if it's a well answered question and I've just glossed over the google solution!

Thanks in advance!

Edit: Looking a bit further into it, does it have something to do with get/set?

A Tartan Tory fucked around with this message at 12:09 on Aug 22, 2014

Dumlefudge
Feb 25, 2013

quote:

And how to convert it from (presumably a string) to a double?

The conversion can be done using Double.Parse or Double.TryParse e.g.
code:
try
{
    double x = Double.Parse(str);
    //use x
}
catch (Exception ex)
{
    //can't parse the string
}
or

code:
double x;
if (Double.TryParse(str, out x))
{
    //use x
}
else
{
    //can't parse, x is set to 0
}
Additionally, there are a number of overloads for both methods (MSDN link) to accommodate specific number formats.

I can't offer much help in the WPF side of your problem, unfortunately, since I don't know a whole lot of it myself and I don't want to steer you in the wrong direction with my own terrible ideas.

Dumlefudge fucked around with this message at 12:27 on Aug 22, 2014

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Have you read this link in the OP?

http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

Have you implemented INotifyPropertyChanged on your viewmodel? You're not giving a lot of information to help point you in the right direction. Do you have any code you can post?

Che Delilas
Nov 23, 2009
FREE TIBET WEED

How much do you want to learn? I ask because what you're talking about doing is more or less the essential foundation of good WPF coding. If this is just a one-off project and all you care about is getting it to work, there are quick and dirty ways. If you actually want to learn WPF and how to do things the "right" way, you're going to need to learn and understand the design pattern called MVVM, which is not an easy thing to wrap your mind around if you haven't seen it or something like it before.

Edit: Ithaqua may organize a lynch mob for me if I teach you the quick and dirty way :v:

Gul Banana
Nov 28, 2003

https://github.com/gulbanana/wpfbinding
here's a demo of something similar to what you describe - using data-binding from a textbox to trigger a calculation in code.

i've implemented it in two different ways
1) using an ICommand binding on a Button to explicitly run the calculating code
2) using a property setter to modify another property, which notifies the UI (using INotifyPropertyChanged, as Ithaqua says)

mvvm really doesn't involve a lot of work - check it out and you might be pleasantly surprised

A Tartan Tory
Mar 26, 2010

You call that a shotgun?!

Dumlefudge posted:

The conversion can be done using Double.Parse or Double.TryParse e.g.

Thanks!


Ithaqua posted:

Have you read this link in the OP?

http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

Have you implemented INotifyPropertyChanged on your viewmodel? You're not giving a lot of information to help point you in the right direction. Do you have any code you can post?

Honestly, there is no code I can post, I do just want to learn how to do that specific part because I couldn't see it on all the MS stuff like http://www.wpf-tutorial.com/about-wpf/what-is-wpf/ I had been going through to prepare before I started even thinking about coding. But I see now that it's folded into MVVM.

I will have a look at that OP link though, it definitely looks like the right direction, mostly used to the MVC pattern from my days learning Java so it never even occurred there was a different way of doing it here. I really should properly read op's first.


Che Delilas posted:

How much do you want to learn? I ask because what you're talking about doing is more or less the essential foundation of good WPF coding. If this is just a one-off project and all you care about is getting it to work, there are quick and dirty ways. If you actually want to learn WPF and how to do things the "right" way, you're going to need to learn and understand the design pattern called MVVM, which is not an easy thing to wrap your mind around if you haven't seen it or something like it before.

Edit: Ithaqua may organize a lynch mob for me if I teach you the quick and dirty way :v:

I want to do it the proper way, been there, done that with the quick and dirty and it almost inevitably doesn't work. It isn't so much a one off project as letting me help myself in the future by making desktop apps to make my life easier as a hobby. Seeing as you both mentioned MVVM, it seemed like the best place to start. Actually found a decent starter tutorial on youtube with a lot of examples that has helped me start the basis of it.


Gul Banana posted:

https://github.com/gulbanana/wpfbinding
here's a demo of something similar to what you describe - using data-binding from a textbox to trigger a calculation in code.

i've implemented it in two different ways
1) using an ICommand binding on a Button to explicitly run the calculating code
2) using a property setter to modify another property, which notifies the UI (using INotifyPropertyChanged, as Ithaqua says)

mvvm really doesn't involve a lot of work - check it out and you might be pleasantly surprised

Thank you for your hard work there, it's helped out a lot actually seeing it!

Will take all your suggestions into consideration and start with learning MVVM. Thanks a lot for getting me started guys!

A Tartan Tory fucked around with this message at 15:42 on Aug 22, 2014

Knyteguy
Jul 6, 2005

YES to love
NO to shirts


Toilet Rascal

Che Delilas posted:

It could be a Visual Studio bug - I hate to suggest this because it sounds so Tier 1 Helpdesk, but have you tried Cleaning your solution, exiting Visual Studio, then restarting it and Rebuilding your solution?

I've had VS gently caress up in similar ways in the past, being unable to find classes that I knew were there and the like, specifically with XAML. Restarting the IDE tended to fix it.

Ok it looks like a Visual Studio bug. Perhaps what happened was what GrumpyDoctor was mentioning (compiler couldn't find a file or something). I tried cleaning, closing, rebuilding, all of that multiple times.

What worked was I ended up redownloading the entire source from source control (which still had the error), but after rebuilding it finally worked.

Thanks all for the help. It's difficult to solve a problem like that being so new to the language and not knowing if the code is completely off.

Edit:

Anyone have an opinion on the Telerik tools, http://www.telerik.com/windows-universal-ui, or telerik appbuilder? As a .NET developer who uses their tools - have you found them to be worth the cost?

Knyteguy fucked around with this message at 16:50 on Aug 22, 2014

ljw1004
Jan 18, 2005

rum

Knyteguy posted:

I think this the right place. I'm having some trouble with XAML since I'm completely new to it. Specifically I'm having trouble with the data binding.

I think people make data-binding more difficult than it need be. Here's how I'd write your code...

XML code:
<Page
    x:Class="CompanyWidgetMobileApp.MarginCalculatorPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:CompanyWidgetMobileApp"
    xmlns:data="using:CompanyWidgetMobileApp.Data"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Page.Resources>
        <data:SampleMarginData x:Key="data1"/>
    </Page.Resources>


    <ListView x:Name="list1" d:DataContext="{StaticResource data1}" ItemsSource="{Binding}">
      <ListView.ItemTemplate>
        <DataTemplate>
          <Grid Background="DarkBlue">
            <TextBlock VerticalAlignment="Top" Text="{Binding Item}"/>
            <TextBlock VerticalAlignment="Bottom" Text="{Binding SalesCost}"/>
            <Image HorizontalAlignment="Right" Source="{Binding Price}"/>
          </Grid>
        </DataTemplate>
      </ListView.ItemTemplate>
    </ListView>
</Page>
This means: (1) Instantiate an instance of the "SampleMarginData" class and have this instance go by the name "data1". (2) At design-time, use "data1" as the datacontext for my listview.

(I deleted all the data-context stuff you had)

(3) At runtime, in my page constructor on Loaded or OnNavigatedTo event, then I'd bind list1.DataContext to my actual runtime datacontext.

And here's the code I'd write:

C# code:
namespace CompanyWidgetMobileApp.Data
{
    public partial class MarginModel
    {
        public ItemModel Item {get; set;}
        public double SalesCost {get; set;}
        public double SalesPrice {get; set;}
    }

    public class SampleMarginData : ObservableCollection<MarginModel>
    {
        public SampleMarginData()
        {
           Add(new MarginModel {Item=new ItemModel(), SalesCost=23.1, SalesPrice=17.9});
           Add(new MarginModel {Item=new ItemModel(), SalesCost=11.1, SalesPrice=23.1});
        }
    }
}
I've written the "MarginModel" class using auto-properties, which the compiler treats as a syntactic shortcut for the longhand form of the properties that you were writing out in full.



Why do people use json for their sample data? Beats me.



CAVEAT: I've not used sub-namespaces within XAML. So I don't know if this "xmlns:data" declaration is the right way to do it. I generally stick all my stuff just in the main project namespace, and so my XAML would have "<local:SampleMarginData x:Key="data1"/>"

Drastic Actions
Apr 7, 2009

FUCK YOU!
GET PUMPED!
Nap Ghost

ljw1004 posted:

Why do people use json for their sample data? Beats me.

I think Blend does that if you ask it to create sample data based on your entities.

Knyteguy
Jul 6, 2005

YES to love
NO to shirts


Toilet Rascal

ljw1004 posted:

I think people make data-binding more difficult than it need be. Here's how I'd write your code...

I'm refactoring now to try it out. Thanks.

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

ljw1004 posted:

C# code:
public class SampleMarginData : ObservableCollection<MarginModel>

A note: It's generally a bad practice to subclass collections.
http://stackoverflow.com/questions/21692193/why-not-inherit-from-listt

Factor Mystic
Mar 20, 2006

Baby's First Post-Apocalyptic Fiction

Ithaqua posted:

A note: It's generally a bad practice to subclass collections.
http://stackoverflow.com/questions/21692193/why-not-inherit-from-listt

Aside from the non-generic subclass, I'll give the benefit of the doubt to anyone subclassing ObservableCollections since the base class is so irritating. Who's using OC<T> and NOT subclassing it?

Gul Banana
Nov 28, 2003

Factor Mystic posted:

Aside from the non-generic subclass, I'll give the benefit of the doubt to anyone subclassing ObservableCollections since the base class is so irritating. Who's using OC<T> and NOT subclassing it?

in my current project, we've got both FastObservableCollection and SlightlyObservableCollection

Sab669
Sep 24, 2009

Any of you guys know what would be the easiest way to downgrade an MSBuild installation? Having some issues with a handful of scripts on my machine that work on a coworkers, my version of MSBuild is slight newer and we're pretty sure that's the issue.

crashdome
Jun 28, 2011
This isn't a question as much as an op-ed post because I am really hating the project I am doing right now. I really have to say that working in .Net has sufficiently spoiled me. I mean, we all have our complaints about it but, I am doing a project in C using a customized Eclipse IDE (for code generation) and I feel like I went back in time to the building of the pyramids. The language/franework is certainly sound. It's the complete lack of anything other than a pretty color on syntax that is frustrating me. No auto-complete. No Intellisense. Can't even use project references without writing weird makefiles. Seperation of concerns is *almost* impossible due to their custom compiler. The documentation for the framework is laughable. They have a "wiki" which is more like 4 pages of FAQs but, instead of actual FAQs, it's sales pitches. The "tools" aren't even customizable. They code generate a bunch of generic "example" files and basically tell you that you have about 100 years of work ahead getting it all to your liking. Find/Replace all day! Yay! I could hunt down Eclipse plug-ins for all this but, instead I am trying to integrate their tools into Visual Studio since it will probably take just as long.

So thank you Microsoft for having the best online documentation I have personally ever used. Thank you .Net community for the awesome tools that are space-age compared to this. And thank you Visual Studio for being flexible enough that I can take this horrible projects tools and integrate them into you like the *wonderful accommodating partner* that you are.

crashdome fucked around with this message at 01:33 on Aug 26, 2014

mortarr
Apr 28, 2005

frozen meat at high speed

Knyteguy posted:

Anyone have an opinion on the Telerik tools, http://www.telerik.com/windows-universal-ui, or telerik appbuilder? As a .NET developer who uses their tools - have you found them to be worth the cost?

My team have been using telerik devcraft for the last year or so, and although I've not used the win ui stuff (just the asp.net mvc and kendo ui).

I've found they keep their tools up to date, they have good response times to posts in their own forums, they do quarterly releases plus fairly regular updates in between times. I think for the most part their getting started and api docs are good, certainly enough to get something of medium complexity/sophistication going, and from there you can hit their forums or stack overflow. They do webinars every now and then about the devcraft toolset, although I've not taken part in one so far.

I've not tried any alternatives and I can't remember why we chose telerik in the first place, but the controls themselves are way better than the VS defaults or hacking together a bunch of open source components that were never designed to fit together. With that plus the support you get with paid-for tools, I think they're pretty sweet.


Edit:

That particular product is in beta, and there are only a few components, but you might be interested to know that kendo ui has had maybe 10-15 controls added in the last year, so I would expect they'll release a bunch of extra controls plus enhancements to existing ones over the next few months - it looks like they're coming out of beta in October too.

mortarr fucked around with this message at 23:03 on Aug 24, 2014

NoDamage
Dec 2, 2000
Progress on our Windows version is going smoothly, so now I am having to consider some aspects of app distribution that were previously taken care of with the App Store model. Does anyone have experience/thoughts/advice on selling traditional (consumer) desktop Windows apps, particularly with regards to payment processing/licensing/automatic updating?

For payments I was thinking of going with FastSpring, licensing I have no idea but I'm not particularly inclined to roll my own, and for automatic updating I was hoping something like Sparkle existed for Windows but it doesn't seem like there is anything robust/currently maintained.

NickFendon
May 4, 2009

NoDamage posted:

Progress on our Windows version is going smoothly, so now I am having to consider some aspects of app distribution that were previously taken care of with the App Store model. Does anyone have experience/thoughts/advice on selling traditional (consumer) desktop Windows apps, particularly with regards to payment processing/licensing/automatic updating?

For payments I was thinking of going with FastSpring, licensing I have no idea but I'm not particularly inclined to roll my own, and for automatic updating I was hoping something like Sparkle existed for Windows but it doesn't seem like there is anything robust/currently maintained.

We use LimeLM for licensing. They aren't a big company but the product works well and they've been on the ball with their support whenever we've needed it.

A lot of people would disagree with this, but I legitimately love ClickOnce for app deployment and automatic updating. I use it whenever I can. We've also used wyBuild on a few products - it works well but is a pain to script/automate.

NoDamage
Dec 2, 2000

NickFendon posted:

We use LimeLM for licensing. They aren't a big company but the product works well and they've been on the ball with their support whenever we've needed it.

A lot of people would disagree with this, but I legitimately love ClickOnce for app deployment and automatic updating. I use it whenever I can. We've also used wyBuild on a few products - it works well but is a pain to script/automate.
How long have you been using LimeLM? Have they been reliable? Their product looks pretty nice, but I'm always a bit wary about adding a third-party dependency, especially one that depends on someone else's servers for activation.

NickFendon
May 4, 2009

NoDamage posted:

How long have you been using LimeLM? Have they been reliable? Their product looks pretty nice, but I'm always a bit wary about adding a third-party dependency, especially one that depends on someone else's servers for activation.

Been using them for 2-3 years, I think. Haven't had any issues with their servers so far. I believe they'll let you self-host it or get their source code held in escrow as protection against them going out of business or whatever. In an ideal world I'd probably prefer to roll my own system, because we have some weird edge cases that no off-the-shelf system can deal with perfectly, but LimeLM has been pretty good to us so far.

Doghouse
Oct 22, 2004

I was playing Harvest Moon 64 with this kid who lived on my street and my cows were not doing well and I got so raged up and frustrated that my eyes welled up with tears and my friend was like are you crying dude. Are you crying because of the cows. I didn't understand the feeding mechanic.
I've been working with the TFS API in C# a bit recently, but now I'm trying to move an iteration node from one root node to another. You can easily do this in the web tfs interface, just by dragging and dropping. Is there a way to do it with C#?
I can get the root node objects and the child node objects but they don't seem to be able to do anything.

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Doghouse posted:

I've been working with the TFS API in C# a bit recently, but now I'm trying to move an iteration node from one root node to another. You can easily do this in the web tfs interface, just by dragging and dropping. Is there a way to do it with C#?
I can get the root node objects and the child node objects but they don't seem to be able to do anything.

I don't think that's an option. I'm almost afraid to ask why you're trying to programmatically move iterations around, though.

Dietrich
Sep 11, 2001

Microsoft's new DocumentDB looks both awesome and terrifying at the same time, but I have to ask myself why I would use it over something like RavenDB or MongoDB which would work anywhere.

A Tartan Tory
Mar 26, 2010

You call that a shotgun?!

Gul Banana posted:

https://github.com/gulbanana/wpfbinding
here's a demo of something similar to what you describe - using data-binding from a textbox to trigger a calculation in code.

i've implemented it in two different ways
1) using an ICommand binding on a Button to explicitly run the calculating code
2) using a property setter to modify another property, which notifies the UI (using INotifyPropertyChanged, as Ithaqua says)

mvvm really doesn't involve a lot of work - check it out and you might be pleasantly surprised

For this example, using your first method of direct command binding. How would I go about using multiple inputted variables and displaying them? Everything I have tried from what I know of c# so far has not worked in changing it.

As an example of what I'm trying to do, here is the following. Using inputted years and months int variables from the user in order to do a loop, which I can use to populate array values to display to the user. It is telling me I can't use calculate and I can't figure out why.

code:
      <Label DockPanel.Dock="Left" FontWeight="Bold" Content="Years:"/>
            <TextBox DockPanel.Dock="Left" MinWidth="100" Text="{Binding Years, StringFormat=G}"/>
            <Label DockPanel.Dock="Left" FontWeight="Bold" Content="Months:"/>
            <TextBox DockPanel.Dock="Left" MinWidth="100" Text="{Binding Months, StringFormat=G}"/>
            <Button HorizontalAlignment="Right" Content="Calculate" Command="{Binding DoCalculate}" CommandParameter="{Binding}"/>
code:
    class Model : BindableBase
    {
        private int years;
        public int Years
        {
            get { return years; }
            set { SetProperty(ref years, value); }
        }

        private int months;
        public int Months
        {
            get { return months; }
            set { SetProperty(ref months, value); }
        }
code:
        private IEnumerable<CalculatedResult> Calculate(int years, int months)
        {
            int y = 0;
            int m = 0;
            for (y = 0; y < years; y++)
            {
                    for (m = 0; m < 12; m++)
                    {
                        if(y == 0 && m == 0)
                            {
                            calculation
                            }
                        else if (y != 0 && m == 0)
                            {
                            calculation
                            }
                        else
                            {
                            calculation
                            }
                    }
                
            }

                        for (m = 0; m < months; m++)
                            {
                                if (m == 0)
                                {
                                calculation
                                }
                                else
                                {
                                calculation
                                }
                            }

        private void Model_DoCalculate(Model viewModel)
        {
            viewModel.CalculatedResults = Calculate(viewModel.Years);
        }
    }
Whereas I can do it quite easily just using the console (to give you a better idea of what I'm trying to convert to WPF).

code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestLoop3
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.Write("Enter the number of years:  ");
            Console.Write(" ");
            string yearsasastring = Console.ReadLine();
            int Years = Convert.ToInt32(yearsasastring);

            Console.Write("Enter the number of months:  ");
            Console.Write(" ");
            string monthsasastring = Console.ReadLine();
            int Months = Convert.ToInt32(monthsasastring);

            double AMC = 0.002;
            double Initialcharge = 0.002;
            double Premium = 100;
            double AIR = 0.04;
            double Openingreserve = 10000;
            double RDR = 0.03;
            double Expenses = 30;
            double EIP = 0.025;

            double[,] URCharges = new double[Years + 1, Years * 12 + Months];
            double[,] UnitReserve = new double[Years + 1, Years * 12 + Months];
            double[,] SRExpenses = new double[Years + 1, Years * 12 + Months];
            double[,] SRCF = new double[Years + 1, Years * 12 + Months];
            double[,] SRDiscFact = new double[Years + 1, Years * 12 + Months];

            int y = 0;
            int m = 0;
            double AIRMcalc = Math.Pow((1 + RDR), 0.08333333333);
            double AIRM = AIRMcalc - 1;


            for (y = 0; y < Years; y++)
            {
                    for (m = 0; m < 12; m++)
                    {
                        if(y == 0 && m == 0)
                            {
                                Console.WriteLine(" ");
                                URCharges[y, m] = AMC * Openingreserve / 12 + Initialcharge * Premium;
                                UnitReserve[y, m] = Openingreserve * (1 + AIRM) + Premium - URCharges[y, m];

                                SRExpenses[y, m] = Expenses / 12 * Math.Pow((1 + EIP), y);
                                SRCF[y, m] = SRExpenses[y, m] - URCharges[y, m];
                                SRDiscFact[y, m] = Math.Pow((1 + AIRM), -(((y + 1) * 12) - (12 - (m + 1))));

                                Console.WriteLine("Year: " + (y + 1) + " Month: " + (m + 1) + " Unit Charge: " + (URCharges[y, m]) + " Unit Reserve: " + (UnitReserve[y, m]));;
                                Console.WriteLine("Expenses: " + (SRExpenses[y, m]) + " SRCF : " + (SRCF[y, m]) + " DiscFact: " + (SRDiscFact[y, m]));
                            }
                        else if (y != 0 && m == 0)
                            {
                                Console.WriteLine(" ");
                                URCharges[y, m] = AMC * UnitReserve[y - 1, m + 11] / 12 + Initialcharge * Premium;
                                UnitReserve[y, m] = UnitReserve[y - 1, m + 11] * (1 + AIRM) + Premium - URCharges[y, m];

                                SRExpenses[y, m] = Expenses / 12 * Math.Pow((1 + EIP), y);
                                SRCF[y, m] = SRExpenses[y, m] - URCharges[y, m];
                                SRDiscFact[y, m] = Math.Pow((1 + AIRM), -(((y + 1) * 12) - (12 - (m + 1))));

                                Console.WriteLine("Year: " + (y + 1) + " Month: " + (m + 1) + " Unit Charge: " + (URCharges[y, m]) + " Unit Reserve: " + (UnitReserve[y, m]));
                                Console.WriteLine("Expenses: " + (SRExpenses[y, m]) + " SRCF : " + (SRCF[y, m]) + " DiscFact: " + (SRDiscFact[y, m]));
                            }
                        else
                            {
                                Console.WriteLine(" ");
                                URCharges[y, m] = AMC * UnitReserve[y, m - 1] / 12 + Initialcharge * Premium;
                                UnitReserve[y, m] = UnitReserve[y, m - 1] * (1 + AIRM) + Premium - URCharges[y, m];

                                SRExpenses[y, m] = Expenses / 12 * Math.Pow((1 + EIP), y);
                                SRCF[y, m] = SRExpenses[y, m] - URCharges[y, m];
                                SRDiscFact[y, m] = Math.Pow((1 + AIRM), -(((y + 1) * 12) - (12 - (m + 1))));
                                
                                Console.WriteLine("Year: " + (y + 1) + " Month: " + (m + 1) + " Unit Charge: " + (URCharges[y, m]) + " Unit Reserve: " + (UnitReserve[y, m]));
                                Console.WriteLine("Expenses: " + (SRExpenses[y, m]) + " SRCF : " + (SRCF[y, m]) + " DiscFact: " + (SRDiscFact[y, m]));
                            }
                    }
                
            }

                        for (m = 0; m < Months; m++)
                            {
                                if (m == 0)
                                {
                                    Console.WriteLine(" ");
                                    URCharges[Years, m] = AMC * UnitReserve[Years - 1, m + 11] / 12 + Initialcharge * Premium;
                                    UnitReserve[Years, m] = UnitReserve[Years - 1, m + 11] * (1 + AIRM) + Premium - URCharges[Years, m];

                                    SRExpenses[y, m] = Expenses / 12 * Math.Pow((1 + EIP), Years);
                                    SRCF[y, m] = SRExpenses[y, m] - URCharges[y, m];
                                    SRDiscFact[y, m] = Math.Pow((1 + AIRM), -(((y + 1) * 12) - (12 - (m + 1))));

                                    Console.WriteLine("Year: " + (Years + 1) + " Month: " + (m + 1) + " Unit Charge: " + (URCharges[Years, m]) + " Unit Reserve: " + (UnitReserve[Years, m]));
                                    Console.WriteLine("Expenses: " + (SRExpenses[y, m]) + " SRCF : " + (SRCF[y, m]) + " DiscFact: " + (SRDiscFact[y, m]));
                                }
                                else
                                {
                                    Console.WriteLine(" ");
                                    URCharges[Years, m] = AMC * UnitReserve[Years, m - 1] / 12 + Initialcharge * Premium;
                                    UnitReserve[Years, m] = UnitReserve[Years, m - 1] * (1 + AIRM) + Premium - URCharges[Years, m];

                                    SRExpenses[y, m] = Expenses / 12 * Math.Pow((1 + EIP), Years);
                                    SRCF[y, m] = SRExpenses[y, m] - URCharges[y, m];
                                    SRDiscFact[y, m] = Math.Pow((1 + AIRM), -(((y + 1) * 12) - (12 - (m + 1))));

                                    Console.WriteLine("Year: " + (Years + 1) + " Month: " + (m + 1) + " Unit Charge: " + (URCharges[Years, m]) + " Unit Reserve: " + (UnitReserve[Years, m]));
                                    Console.WriteLine("Expenses: " + (SRExpenses[y, m]) + " SRCF : " + (SRCF[y, m]) + " DiscFact: " + (SRDiscFact[y, m]));
                                }
                            }

            Console.ReadKey();
        }
    }

A Tartan Tory fucked around with this message at 19:07 on Aug 26, 2014

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug
You're misunderstanding how MVVM works, I think.

Your viewmodel represents the state of your view, and exposes properties (sometimes in the form of model objects, sometimes not) that are bound to the view.

You should have your button bound to an ICommand implementation in your viewmodel. When you click the button, it calls the method in your viewmodel. The viewmodel then does "stuff", and updates its properties (or model objects) based on the results of that stuff. Since you've bound properties to the view, the view will automatically update as your viewmodel and model changes.

raminasi
Jan 25, 2005

a last drink with no ice
The whole process is made harder than it needs to be by the fact that WPF doesn't offer a good, concrete ICommand implementation out of the box, for some idiotic reason. Most people either use third-party frameworks or just roll the bits from them they need on their own, like the RelayCommand in this article. (RelayCommand is really tiny so it's not hard.)

The end product looks something like this:
C# code:
public class ViewModel : INotifyPropertyChanged
{
    public ICommand CalculateCommand { get; private set; }

    public ViewModel()
    {
        CalculateCommand = new RelayCommand(Calculate);
    }

    private void Calculate()
    {
        // Perform whatever calculation and property assignment is necessary.
        // Remember that you have access to all the data-bound properties you need to serve as calculation inputs.
    }

    // blah blah blah whatever else
}

A Tartan Tory
Mar 26, 2010

You call that a shotgun?!

Ithaqua posted:

You're misunderstanding how MVVM works, I think.

Your viewmodel represents the state of your view, and exposes properties (sometimes in the form of model objects, sometimes not) that are bound to the view.

You should have your button bound to an ICommand implementation in your viewmodel. When you click the button, it calls the method in your viewmodel. The viewmodel then does "stuff", and updates its properties (or model objects) based on the results of that stuff. Since you've bound properties to the view, the view will automatically update as your viewmodel and model changes.

As far as I understand, with this example, the controller is the viewmodel? The button push just tells it to get the Calculated Results? What I should be doing is telling the button to implement a command rather than to get existing results? I'm getting really confused now!

View passes information to viewmodel, viewmodel updates model, model updates viewmodel, viewmodel updates view? Is that supposed to be how it works?


GrumpyDoctor posted:

The whole process is made harder than it needs to be by the fact that WPF doesn't offer a good, concrete ICommand implementation out of the box, for some idiotic reason. Most people either use third-party frameworks or just roll the bits from them they need on their own, like the RelayCommand in this article. (RelayCommand is really tiny so it's not hard.)

The end product looks something like this:
C# code:
public class ViewModel : INotifyPropertyChanged
{
    public ICommand CalculateCommand { get; private set; }

    public ViewModel()
    {
        CalculateCommand = new RelayCommand(Calculate);
    }

    private void Calculate()
    {
        // Perform whatever calculation and property assignment is necessary.
        // Remember that you have access to all the data-bound properties you need to serve as calculation inputs.
    }

    // blah blah blah whatever else
}

Ok so, this is the viewmodel, it initiates itself whenever the button is pressed (how do I represent that in the XAML in view?) and all the inputted data is bound to the name I use in the xaml in view for that textbox it just needs to be assigned to a new variable within this method (how do I access it from the binding to do that then, it can't be within the model as given in the example?).

A Tartan Tory fucked around with this message at 19:25 on Aug 26, 2014

Knyteguy
Jul 6, 2005

YES to love
NO to shirts


Toilet Rascal

A Tartan Tory posted:

Ok so, this is the viewmodel, it initiates itself whenever the button is pressed (how do I represent that in the XAML in view?) and all the inputted data is bound to the name I use in the xaml in view for that textbox it just needs to be assigned to a new variable within this method (how do I access it from the binding to do that then, it can't be within the model as given in the example?).

<Button Command="{Binding CalculateCommand}" ... /> would be the XAML to hook to the command.

I was struggling with a lot of these same questions just yesterday. Check out:
https://www.youtube.com/watch?v=EpGvqVtSYjs

I found it pretty helpful coming from an MVC background and being new to MVVM/WPF. It goes into binding, it shows an ICommand implementation, etc.

Knyteguy fucked around with this message at 19:34 on Aug 26, 2014

raminasi
Jan 25, 2005

a last drink with no ice

A Tartan Tory posted:

Ok so, this is the viewmodel, it initiates itself whenever the button is pressed (how do I represent that in the XAML in view?) and all the inputted data is bound to the name I use in the xaml in view for that textbox it just needs to be assigned to a new variable within this method (how do I access it from the binding to do that then, it can't be within the model as given in the example?).

It doesn't need to be assigned anywhere new; presumably you've got some of these guys elsewhere in your viewmodel:
C# code:

    private IEnumerable<CalculatedResult> results;
    private int months;
    private int years;

    public IEnumerable<CalculatedResult> Results
    {
        get { return results; }
        set
        {
            results = value;
            // Most people do a null check here but I'm eliding that for simplicity
            // (And because there's a better way to do it)
            PropertyChanged(this, new PropertyChangedEventArgs("Results"));
        }
    }

    public int Months
    {
        get { return months; }
        set
        {
            months = value;
            PropertyChanged(this, new PropertyChangedEventArgs("Months"));
        }
    }

    public int Years
    {
        get { return years; }
        set
        {
            years = value;
            PropertyChanged(this, new PropertyChangedEventArgs("Years"));
        }
    }

that you've databound to. The body of Calculate will then have access to this.Months and this.Years as calculation arguments, and this.Results to stuff the results in.

A Tartan Tory
Mar 26, 2010

You call that a shotgun?!

GrumpyDoctor posted:

It doesn't need to be assigned anywhere new; presumably you've got some of these guys elsewhere in your viewmodel:

that you've databound to. The body of Calculate will then have access to this.Months and this.Years as calculation arguments, and this.Results to stuff the results in.

Oh, oh! I get it now! So whenever the view is updated by the user, the command updates the variables that are assigned in public in the ViewModel, so it can be used by the programming logic later on and then displayed as results when finished?

If I was to stuff multiple arrays into this.results though, would it still work if it was shown in view in the correct way?

raminasi
Jan 25, 2005

a last drink with no ice

A Tartan Tory posted:

Oh, oh! I get it now! So whenever the view is updated by the user, the command updates the variables that are assigned in public in the ViewModel, so it can be used by the programming logic later on and then displayed as results when finished?

If I was to stuff multiple arrays into this.results though, would it still work if it was shown in view in the correct way?

Not quite. The command doesn't do the updating; the data binding engine itself does that. It would still work even if there were no command anywhere.

If you perform multiple assignments to Results, only the last one will "stick," the same as any other variable assignment.

Mr. Crow
May 22, 2008

Snap City mayor for life
Fourth'ing the conclusion you don't understand MVVM and are making this way more complicated than it needs to be.

Super high-level; your View-Model consumes your Model, your View consumes your View-Model, your Model knows nothing about your View-Model or View, your View-Model knows nothing about your View (there's debate on this specific point, I guess), your View knows nothing about your Model.

So exactly like a lot of what gets said about MVVM, the View-Model is the glue between your UI and your Business Logic.

A Tartan Tory posted:

The button push just tells it to get the Calculated Results? What I should be doing is telling the button to implement a command rather than to get existing results?

Your View-Model exposes/provides some sort of general ICommand property, that the View (or multiple views) consumes to perform some action. ICommands are literally just delegates with built-in if-checks (e.g. CanExecute, usually you don't even need this) in the majority case. There is nothing special about them beyond that they are heavily built into the framework to make it easy to delegate function calls, which is why a lot of Controls have a Command property.

There are also RoutedUICommands which are basically RoutedEvents + RelayCommands (linked above and re-implemented ad-nauseum across the internet), which is what is built into WPF (RoutedUICommands). Ignore these.

quote:

View passes information to viewmodel, viewmodel updates model, model updates viewmodel, viewmodel updates view? Is that supposed to be how it works?

More or less.


quote:

Ok so, this is the viewmodel, it initiates itself whenever the button is pressed (how do I represent that in the XAML in view?) and all the inputted data is bound to the name I use in the xaml in view for that textbox it just needs to be assigned to a new variable within this method (how do I access it from the binding to do that then, it can't be within the model as given in the example?).

You create your View and your ViewModel independently of each other and tell your View to consume a ViewModel by setting the Views DataContext property to whatever ViewModel.

A Tartan Tory
Mar 26, 2010

You call that a shotgun?!
Right, so if I understand this correctly now, the only way ViewModel and View interact is through data binding for both getting the user inputted variables and sending the results back. The viewmodel has the programming logic and the model has the business logic behind it (ViewModel and Model are linked).

So to do what I need to do, I need to get my inputs from View to Viewmodel using data binding, run it through the programming logic in there, then spit it back out through data binding again.

Dietrich
Sep 11, 2001

A Tartan Tory posted:

Right, so if I understand this correctly now, the only way ViewModel and View interact is through data binding for both getting the user inputted variables and sending the results back. The viewmodel has the programming logic and the model has the business logic behind it (ViewModel and Model are linked).

So to do what I need to do, I need to get my inputs from View to Viewmodel using data binding, run it through the programming logic in there, then spit it back out through data binding again.

Exactly.

And then you can write unit-tests against your ViewModel or have multiple views of the same ViewModel with different controls or designs without having to change any code.

Gul Banana
Nov 28, 2003

A Tartan Tory posted:

So to do what I need to do, I need to get my inputs from View to Viewmodel using data binding, run it through the programming logic in there, then spit it back out through data binding again.

That's right- the only thing I'd add to this summary is that it's not a procedural process. You *declare* bindings, typically in XAML, rather than actually *executing* code which moves data around, and then the rest is taken care of.

It's not magic, mind you. The binding system is just listening for events from the INotifyPropertyChanged interface (or a couple of alternatives)- but in effect, the view and viewmodel are just always synchronised, and the problem is reduced to how to manipulate the data in the viewmodel.

The class I called Controller in the sample code was just a place to do that, and ICommands are just a kind of data which is itself bound - rather than a string or a number, they represent an action to potentially take.

Adbot
ADBOT LOVES YOU

crashdome
Jun 28, 2011

Gul Banana posted:

It's not magic, mind you.

I'm pretty sure it's a religious conviction though because of all the faith involved and the sinful behaviors that are committed on a daily basis :can:

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply